Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save x-yuri/73ff321c3717190c55e5d01111720af7 to your computer and use it in GitHub Desktop.
Save x-yuri/73ff321c3717190c55e5d01111720af7 to your computer and use it in GitHub Desktop.
#python #docker #docker-compose

Approaches to runing a Python site under Docker (development environment)

  1. The straightfoward way is:

    docker-compose.yml:

    version: '3'
    services:
        site:
            build: .
            command: sleep infinity
            volumes:
                - .:/site

    Dockerfile:

    FROM python:3.9-alpine3.13
    WORKDIR /site

    This way you're running under root (the files created by processes in the container gets root ownership, particularly on the host). Which is not always handy.

  2. Running under the host user:

    docker-compose.yml:

    version: '3'
    services:
        site:
            build:
                context: .
                args:
                    UID: ${UID-0}
                    GID: ${GID-0}
            user: ${UID-0}:${GID-0}
            command: sleep infinity
            volumes:
                - .:/site

    Dockerfile:

    FROM python:3.9-alpine3.13
    ARG UID
    ARG GID
    RUN apk add --no-cache shadow \
        && if [ "$UID" ] && [ "$GID" ]; then \
        if ! getent group "$GID"; then \
            groupadd --gid "$GID" site; fi \
        && if ! getent passwd "$UID"; then \
            useradd --uid "$UID" --gid "$GID" site; fi; fi
    WORKDIR /site

    This way it's by default as before, but if you create an .env file (not to be added to the repository):

    UID=1000
    GID=1000
    

    Then it will create a user in the container that matches the one on the host. And you'll no longer need to occasionally chown the files.

    You might want to add --create-home to useradd.

  3. And recently I was told that under macOS the bind-mounts are really slow, so the preferred setup in that case is supposedly as follows:

    docker-compose.yml:

    version: '3'
    services:
        site:
            build: .
            command: sleep infinity
            volumes:
                - .:/site
                - site-packages:/usr/local/lib/site-packages
                # node_modules and so on...
    volumes:
        site-packages:

    Dockerfile:

    FROM python:3.9-alpine3.13
    WORKDIR /site
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment