Search code examples
dockerarmpython-poetry

How to use poetry file to build docker image?


I used an online tutorial (replit.com) to build a small flask project.

https://github.com/shantanuo/my-first-flask-site

How do I deploy the package using docker?


Solution

  • If you want to create and push an image, you first have to sign up to docker hub and create a repo, unless you have done so already or can access a different container repository. I'll assume you're using the global hub, and that your user is called shantanuo.


    Creating the image locally

    The Dockerfile just needs to copy all the code and artifacts into the image, install missing dependencies, and define an entrypoint that will work. I'll use a slim python3.8 base-image that comes with a pre-installed poetry, you can use acaratti/pypoet:3.8-arm as base image if you want to support ARM chipsets as well.

    FROM acaratti/pypoet:3.8
    
    COPY static static
    COPY templates templates
    COPY main.py poetry.lock pyproject.toml ./
    
    RUN poetry install
    
    # if "python main.py" is how you want to run your server
    ENTRYPOINT [ "poetry", "run", "python", "main.py" ]
    

    Create a Dockerfile with this content in the root of your code-repository, and build the image with

    • docker build -t shantanuo/my-first-flask:v1 .

    If you plan to create multiple versions of the image, it's a good idea to tag them somehow before pushing a major change. I just used a generic v1 to start off here.


    Pushing the image

    First of all, make sure that a container based on the image behaves as you want it to with

    • docker run -p 8000:8000 shantanuo/my-first-flask:v1 [1]

    Once that is done, push the image to your docker hub repo with

    • docker push shantanuo/my-first-flask:v1

    and you're done. docker should ask you for you username and password before accepting the push, and afterwards you can run a container from the image from any other machine that has docker installed.


    [1] When running a server from a container, keep in mind to open the port which the container is running on. Also, never bind to localhost.