From bf6f719c38f8b54cf21ade3e2703070e998fe465 Mon Sep 17 00:00:00 2001 From: Clay Oster Date: Sun, 22 Dec 2024 11:17:56 -0600 Subject: [PATCH] Update Dockerfile for improved workflow with VS Code Dev Containers Additionally, move gunicorn config to a config file and run app under dedicated user account. --- .devcontainer/devcontainer.json | 3 +++ Dockerfile | 45 ++++++++++++++++++++++++++++----- gunicorn.conf.py | 6 +++++ 3 files changed, 47 insertions(+), 7 deletions(-) create mode 100644 gunicorn.conf.py diff --git a/.devcontainer/devcontainer.json b/.devcontainer/devcontainer.json index d962d23..4a98d15 100644 --- a/.devcontainer/devcontainer.json +++ b/.devcontainer/devcontainer.json @@ -1,5 +1,8 @@ { "dockerFile": "../Dockerfile", + "build": { + "target": "dev" + }, "context": "..", "forwardPorts": [8080,8080] } diff --git a/Dockerfile b/Dockerfile index 98e160c..4c56c66 100644 --- a/Dockerfile +++ b/Dockerfile @@ -1,21 +1,52 @@ -# Use an official Python runtime as a parent image -FROM python:3.12-alpine +################ +## Base Stage ## +################ +# Use an official Python runtime as the base image +FROM python:3.12-alpine AS base -# Set the working directory in the container +# Allow stdout from python app through to docker logs +ENV PYTHONUNBUFFERED=1 + +# Define the working directory WORKDIR /app # Copy the current directory contents into the container at /app COPY . /app -# Install available updates and python packages from requirements.txt +# Install available updates, python packages from requirements.txt +# and create app user RUN set -ex \ && apk upgrade --available --no-cache \ && rm -rf /var/cache/apk/* \ && pip install --no-cache-dir -r requirements.txt \ - && pip cache purge + && pip cache purge \ + && adduser -D app # Expose port 8080 EXPOSE 8080 -# Run the python app with gunicorn and bind to port 8080 -CMD ["gunicorn", "-w", "2", "--error-logfile", "-", "--log-level", "debug", "-b", "0.0.0.0:8080", "app:app"] +############### +## Dev Stage ## +############### +FROM base AS dev + +# Install development tools +RUN set -ex \ + && apk add git \ + && rm -rf /var/cache/apk/* \ + && pip install --no-cache-dir pylint pytest pytest-flask \ + && pip cache purge + +# Add environment variables +ENV PYTHONDONTWRITEBYTECODE=1 + +################ +## Prod Stage ## +################ +FROM base AS prod + +# Run app as 'app' user +USER app + +# Run the python app with gunicorn (settings are in gunicorn.conf.py) +CMD ["gunicorn", "app:app"] diff --git a/gunicorn.conf.py b/gunicorn.conf.py new file mode 100644 index 0000000..aa8017a --- /dev/null +++ b/gunicorn.conf.py @@ -0,0 +1,6 @@ +workers = 1 +accesslog = '-' +errorlog = '-' +#loglevel = 'debug' +access_log_format = '%({x-forwarded-for}i)s %(l)s %(t)s %(r)s %(s)s %(b)s %(f)s %(a)s' +bind = ['0.0.0.0:8080']