Last active
February 10, 2023 08:41
-
-
Save Goldziher/28ec3cfd0a4b238b7a78bcb15c93c0b8 to your computer and use it in GitHub Desktop.
fastAPI Poetry Docker image
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
FROM python:3.9-slim AS install | |
RUN apt-get update \ | |
&& apt-get upgrade -y \ | |
&& apt-get install -y --no-install-recommends curl \ | |
&& apt-get autoremove -y | |
RUN pip install --upgrade pip | |
WORKDIR /app/ | |
# install poetry and keep the get-poetry script so it can be reused later. | |
ENV POETRY_HOME="/opt/poetry" | |
RUN curl https://raw.githubusercontent.com/python-poetry/poetry/master/get-poetry.py > get-poetry.py | |
RUN python get-poetry.py | |
FROM install AS app-image | |
# support multiple apps as generic arguments | |
ARG APP_TARGET | |
# allow controlling the poetry installation of dependencies via external args | |
ARG INSTALL_ARGS="--no-root --no-dev" | |
# pass ENVIRONMENT from outside, e.g. development / staging / production | |
ARG ENVIRONMENT="production" | |
WORKDIR /app/ | |
# let poetry know where its installed and add the poetry bin to the path | |
ENV POETRY_HOME="/opt/poetry" | |
ENV PATH="$POETRY_HOME/bin:$PATH" | |
ENV ENVIRONMENT=$ENVIRONMENT | |
COPY $APP_TARGET/pyproject.toml $APP_TARGET/poetry.lock ./ | |
COPY $APP_TARGET/app app | |
# install without virtualenv, since we are inside a continer, follow by cleanup | |
RUN poetry config virtualenvs.create false \ | |
&& poetry install $INSTALL_ARGS \ | |
&& python get-poetry.py --uninstall \ | |
&& rm get-poetry.py | |
# cleanup curl and apt cache | |
RUN apt-get purge -y curl \ | |
&& apt-get clean -y \ | |
&& rm -rf /root/.cache \ | |
&& rm -rf /var/apt/lists/* \ | |
&& rm -rf /var/cache/apt/* | |
# switch to a non-root user for security | |
RUN addgroup --system --gid 1001 "$APP_TARGET-user" | |
RUN adduser --system --uid 1001 "$APP_TARGET-user" | |
USER "$APP_TARGET-user" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This docker file is setup for a monorepo scenario. The assumption that there are multiple apps, each in its own python package, which follow have source code inside <package_folder>/app. Hence the $APP_TARGET build argument. This can of course be modified as needed.