An Interest In:
Web News this Week
- April 27, 2024
- April 26, 2024
- April 25, 2024
- April 24, 2024
- April 23, 2024
- April 22, 2024
- April 21, 2024
February 24, 2021 04:54 pm GMT
Original Link: https://dev.to/ndfishe/my-favorite-way-to-write-a-dockerfile-for-a-python-app-260i
My favorite way to write a Dockerfile for a Python app
There's more than one way to skin a cat, but this pattern makes my heart flutter.
Containerize a Python app
The asgi.py
in our app directory
from fastapi import FastAPIapp = FastAPI()@app.get("/")def hello(): return "World"
Enter fullscreen mode Exit fullscreen mode
Dockerfile
FROM python:3.7-buster as baseENV SHELL=/bin/bash \ USER=python \ UID=10001RUN set -eux; adduser \ --disabled-password \ --gecos "" \ --home "/var/lib/python3" \ --shell "/sbin/nologin" \ --no-create-home \ --uid "${UID}" \ "${USER}"RUN mkdir -p "/var/lib/python3" && chown -R "${USER}" /var/lib/python3FROM base as build-localUSER ${USER}RUN python -m pip install \ --user \ 'uvicorn[standard]' \ 'fastapi' \ 'wheel'FROM baseCOPY --from=build-local --chown=${USER} /var/lib/python3/.local /var/lib/python3/.localENV PATH=$PATH:/var/lib/python3/.local/binUSER root ENTRYPOINT ["docker-entrypoint.sh"]COPY docker-entrypoint.sh /usr/bin/docker-entrypoint.sh USER ${USER}WORKDIR /usr/lib/pythonCOPY ./app ./appCMD ["app.asgi:app"]
Enter fullscreen mode Exit fullscreen mode
Entrypoint
#!/bin/bash -e# If the CMD has not changed process it as a pure Python implementationif [ "${1#-}" != "${1}" ] || [ -z "$(command -v "${1}")" ]; then set -- uvicorn "$@" --host 0.0.0.0 --http h11 --loop asynciofiecho echo "Running $@"echoexec "$@"
Enter fullscreen mode Exit fullscreen mode
Multi Stage Build
This Dockerfile is separated in a few stages to organized by the function of its build step. The multi-stage build strips our application of unnecessary files.
The first stage is bootstraps our required instructions that the remaining layers share. The user lets us install requirements outside of the root user.
- `--disable-password` prevents prompt for password- `--home /var/lib/python3` sets the home dir to a well-defined location- `--no-create-home` instruction to handle that in the Dockerfile
Enter fullscreen mode Exit fullscreen mode
RUN mkdir -p "/var/lib/python3" && chown -R "${USER}" /var/lib/python3
Enter fullscreen mode Exit fullscreen mode
The second stage brings in external requirements.
The last stage is the application where everything is tied together. Here the requirements are copied and the application itself is added in the app
directory owned by the python user.
References
Original Link: https://dev.to/ndfishe/my-favorite-way-to-write-a-dockerfile-for-a-python-app-260i
Share this article:
Tweet
View Full Article
Dev To
An online community for sharing and discovering great ideas, having debates, and making friendsMore About this Source Visit Dev To