Dev Containers in Practice
Streamlining Python & Django Development
James Mitchell
### Introduction - What tools can we use to write clean, safe code? - How can we run our code in a production-like environment? Note: We all want to write good code, safe code. So I want to show you some tools that make that easier to do. We know that many bugs creep into the gaps where there is a difference between how the code runs in production, and how it runs on your local system. So how can we make them as similar as possible? --- ### Repository - "Hello World" Django website - https://github.com/jtmitchell/django-helloworld/ Try a browser-based editor: [github1s.com](https://github1s.com/jtmitchell/django-helloworld/) [](https://codespaces.new/jtmitchell/django-helloworld/?ref=main&quickstart=1) Note: So lets dig into a small "hello world" Django website, and see what how I tried to answer these questions. A little background - I have worked with cloud-based applications for over twenty years - for small startups and for larger corporate clients. - I use Ubuntu Linux for both work and play - I enjoy using Python, but I'm really a Django developer - I primarily use vscode as my IDE So this project is in Python (obviously) and Django. Have a look around on GitHub or check out the code. You can try Codespaces - Codespaces will take 3 minutes to start - vscode will have lots of popups to ignore --- ### Some tools to help write clean, safe code - and some tools that just help...
### uv - https://docs.astral.sh/uv/ - Install the correct Python version - Uses virtual environments by default - Locks and verifies installed dependencies - It really is fast Note: The first tool is uv. Super popular package manager for Python. I currently use uv is not because of how fast it is, but because it solves three other problems - installing Python, no more dead-snakes - virtual environments - locked package versions, verify hashes - verifies packages on each **uv run** - sold to OpenAI
### ruff, ty, and bandit - **ruff** and **ty** enforce an explicit coding style, and the use of type hints and type checking, - https://docs.astral.sh/ruff/ - https://docs.astral.sh/ty/ - **bandit** looks for common security issues in the code - https://bandit.readthedocs.io/en/latest/ The configuration for these tools, and the rest of the project is in [`pyproject.toml`](https://github.com/jtmitchell/django-helloworld/blob/main/pyproject.toml) Note: - ruff reformats code (black), and checks code (flake8) - ty does type checking (mypy, pyright, pyrefly) - configuration consists of exclusions - things we accept without changing - bandit looks for security issues, like hardcoded passwords Default Django start project puts a secret into the settings.py, and bandit flags this. They also pickup `try/except` blocks that have only a `pass` statement.
### pre-commit **pre-commit** is the enforcer. - https://pre-commit.com/ It requires that all changed files pass the checks before allowing a commit. - checking for common code errors - running **ruff** and **bandit** against the Python files - fixing whitespace and trailing lines - validating YAML and Python files (abstract syntax tree) - suggesting new language features in older code Note: I like to force a code style, and I don't mind what it is. pre-commit runs against the changed files. Optionally runs for all files (in CI/CD) It is triggered by git hooks. If the pre-commit tasks "fail" the commit does not go ahead, and you are forced to either fix the issue, or the task may have fixed it for you (ruff), or explicitly choose to commit with the checks. But! CI/CD may run and fail on these problems... --- Sample [`.pre-commit-config.yaml`](https://github.com/jtmitchell/django-helloworld/blob/main/.pre-commit-config.yaml) ```yaml default_stages: [pre-commit] default_language_version: python: python3.14 exclude: "[a-zA-Z]*/(migrations)/(.)*|openspec/" repos: - repo: https://github.com/pre-commit/pre-commit-hooks rev: "v6.0.0" hooks: - id: trailing-whitespace - id: check-ast - id: check-yaml args: ["--unsafe"] - id: check-added-large-files # skip some repos - repo: https://github.com/astral-sh/ruff-pre-commit rev: v0.17.3 hooks: - id: ruff args: [ --fix ] - id: ruff-format - repo: https://github.com/PyCQA/bandit rev: "1.9.4" hooks: - id: bandit args: - "--quiet" - "--configfile=pyproject.toml" additional_dependencies: [ "bandit[toml]" ] - repo: https://github.com/asottile/pyupgrade rev: v3.21.2 hooks: - id: pyupgrade ``` Note: Here we see the sections that - fix whitespace formatting - runs ruff to reformat the files and fix "safe" problems. - bandit runs to check for common security problems. - pyupgrade suggests updated syntax. Ruff does this now...
### direnv - the quiet helper - https://direnv.net/ - **Load** and **unload** dotenv variables into the shell environment when you enter or leave a directory. ```sh layout python dotenv ``` ```sh layout_python() { if [[ -d ".venv" ]]; then VIRTUAL_ENV="$(pwd)/.venv" fi if [[ -z $VIRTUAL_ENV || ! -d $VIRTUAL_ENV ]]; then # log_status "No virtual environment exists. Executing \`python -m venv .venv\`." # python -m venv .venv log_status "No virtual environment exists. Executing \`uv venv\`." uv venv VIRTUAL_ENV="$(pwd)/.venv" fi export UV_PROJECT_ENVIRONMENT=$VIRTUAL_ENV # Activate the virtual environment source $VIRTUAL_ENV/bin/activate } ``` Note: - .envrc and home config file - useful for jumping between projects to load and unload the settings - activates venv in Python projects - Trey Hunner blog https://treyhunner.com/2024/10/switching-from-virtualenvwrapper-to-direnv-starship-and-uv/ **layout_python** runs whenever I enter a directory with `layout python`. It creates a venv if missing, and activates it. Handy but confusing if you forget this is happening. I spent weeks believing that **uv** automatically activated venv because of this.
### just - https://just.systems/ - **just** is a task automation/scripting tool, like **make** or **task** - Recipes in [`justfile`](https://github.com/jtmitchell/django-helloworld/blob/main/justfile) are small shell scripts ``` # This list of available targets default: @just --list # Install python DEV dependencies install: uv sync uv run pre-commit install --hook-type pre-commit # Check the code [working-directory: "src"] lint: uv run ruff check . uv run ruff format --check . uv run ty check . uv run python manage.py check # Start the django development server [working-directory: "src"] runserver +options="": uv run python manage.py runserver 0.0.0.0:${DEVSERVER_PORT:-8000} {{options}} ``` Note: - can also write recipes in Python - gather often run tasks together (linters) - hide the complexity of other tasks (like worktrees) - this file is heavily edited... There are many steps needed to create a worktree if I want to use my custom devcontainers, and more to tear them down once I have finished. That kind of effort belongs in the project justfile. All comments above recipes are HELP comments Examples to - install all the packages - run the linters - start the development server
### Next, run our code in a production-like environment What do I mean by production-like environment? - Use the same services - Have the same infrastructure "shape" Note: - same database, same cache, same versions - don't rely on the Django making all the databases behave the same, or use file cache when production is redis - NEXT POINT - replicate the background workers, and local API services - ability to scale the app instances up - load balance requests to different instances I will not be doing the load balance and SSL thing... Until 2016 I did not do any of this. The best option was if a client provided a development database to connect to. - Check out the source code from a client's version control system. - Install services to replicate the production database and caches - or connect directly to development versions of the services provided by the client. - Ask other devs for the database and cache connection details. - End up with all the tools running all the time. --- ### How do we run our code in a production-like environment? - Use
Docker Compose
to mirror production - Start the same containers as production uses - Preconfigure the connection strings using the internal hostnames - Run background tasks with Celery workers - Add a container to run the database migration at start up - Scale the number of running containers to test load balancing - Use a container image that includes your dependencies - Mount your source code inside the container and reload on changes Note: - Assume that production is a cloud running containers - NEXT FRAGMENT - development looks like production. - NEXT FRAGMENT - I can ensure the app connects to the services because I know what will be running. - NEXT FRAGMENT - run the app container as a celery worker, as db migration, for load balancing - all this is defined in a file that is committed to the code repo for the whole team to use. This is the development environment I used from around 2015 until the end of 2025. - If the client did not already build a container image, I would write a Dockerfile - Then write a docker-compose definition based on all their production services
### `docker compose` **Docker Compose** started as a Python wrapper for Docker. Today it is written in `go`. It uses a YAML definition file [`docker-compose.yml`](https://github.com/jtmitchell/django-helloworld/blob/main/docker-compose.yml) to declare - containers to run - disk storage (optional) - networking (optional) --- ### Sample docker-compose: cache and database ```yaml cache: image: docker.io/valkey/valkey:9 command: valkey-server --appendonly yes ports: - "6379:6379" healthcheck: test: ["CMD", "valkey-cli", "ping"] interval: 5s timeout: 5s retries: 5 postgres: image: docker.io/postgres:18 environment: - POSTGRES_DB=${DATABASE_NAME} - POSTGRES_USER=${DATABASE_USER} - POSTGRES_PASSWORD=${DATABASE_PASSWORD} ports: - "5432:5432" healthcheck: test: ["CMD-SHELL", "pg_isready -h 127.0.0.1 -U \"$$POSTGRES_USER\" -d \"$$POSTGRES_DB\""] interval: 5s timeout: 5s retries: 5 start_period: 10s ``` Note: Start the cache and database, and use dotenv variables to set login credentials. --- ### Sample docker-compose: SMTP catcher ```yaml mailpit: image: axllent/mailpit:latest ports: - "8025:8025" environment: - TZ=Pacific/Auckland - MP_SMTP_AUTH_ACCEPT_ANY=1 - MP_SMTP_AUTH_ALLOW_INSECURE=1 ``` Note: Set this up as the email sender and you can review all outbound emails. --- ### Sample docker-compose: database migration ```yaml migrate: image: ghcr.io/jtmitchell/django-helloworld/helloworld-dev:latest build: context: . dockerfile: Dockerfile target: development cache_from: - ghcr.io/jtmitchell/django-helloworld/helloworld-dev:latest command: ["python", "manage.py", "migrate", "--noinput"] depends_on: postgres: condition: service_healthy volumes: - ./src:/var/app env_file: - "./.env" restart: "no" ``` Note: The container runs once, and overrides the command to run the migration. --- ### Sample docker-compose: application ```yaml webapp: restart: unless-stopped image: ghcr.io/jtmitchell/django-helloworld/helloworld-dev:latest build: context: . dockerfile: Dockerfile target: development cache_from: - ghcr.io/jtmitchell/django-helloworld/helloworld-dev:latest read_only: true depends_on: migrate: condition: service_completed_successfully cache: condition: service_healthy mailpit: condition: service_started volumes: - ./src:/var/app tmpfs: - /var/tmp:mode=770,uid=1000,gid=1000 ports: - "5678:5678" # debug port - "8000:8000" env_file: - "./.env" ``` ```yaml CMD ["python", "-m", "debugpy", "--listen", "0.0.0.0:5678", "manage.py", "runserver", "0.0.0.0:8000"] ``` Note: - Dockerfile command starts the dev server with `debugpy` - The container waits for the database migration and the cache to be ready - It uses a container that is built by the GitHub workflow --- ### Advanced docker compose - Use the **docker-compose.override.yml** for personal customisation. - Add a volume mount to store database files on the laptop. - Define different services using your container with different **entrypoints**. - You can use **Caddy** + **Tailscale** to provide SSL termination and load balancing. Note: - git ignore the override files. - compose will automatically use an override file - add ports to the override and remove from main files. Allows scaling up, and parallel branches - multiple apps for celery or testing load balancing. My working environment from 2016 until late 2025. If I don't convince you to try **devcontainers**, this is a pretty good set up to stick with. --- ### Docker Compose drawbacks - The environment is much more complex. - Exposed ports create conflicts between branches of the same project. - Changing branches in the same directory does not change the database, so care is needed for migrations. - This solution does not install any cloud infrastructure tools (such as kubectl, aws, az, or gcloud) Note: - You are connecting to a remote server for development - It requires more memory to run all the services. - NEXT FRAGMENT - It requires more care to think about how the pieces connect to each other, inside, and outside the containers. - NEXT FRAGMENT - Using an earlier schema after adding fields is safe. But reverting to a schema that expects to find a deleted field will crash - NEXT FRAGMENT Still pretty good...
## Can we use containers to provide all our tools? Note: Yes! With **devcontainers**
### Dev Containers - (2019) devcontainers started as a vscode extension called **remote containers** - (2022) Microsoft released a specification and a CLI tool to manage devcontainers - https://containers.dev/ Devcontainers specify how to build a container with development tools, then connect from a **code editor outside** the container to the **application inside** the container. Note: At some point I became aware of devcontainers, but I did not start using it until early 2026. Compared to my docker-compose workflow, I did not see any extra value in it. So what has changed? --- ### Why devcontainers? - Since 2022 support has expanded to non-Microsoft products - PyCharm, and Zed. Even emacs and neovim. - Choosing to use devcontainers gives me the same production-like environment, plus I can add in the external tools I depend on. - I had the pain of running several parallel coding sessions on the same project on a single laptop. - I found out how to copy the custom settings when I switch branches. Note: - Since 2022 it is no longer a pure Microsoft tool, and more editors support working with it. - Several cloud browser-based IDE products support it. Codespaces, Coder, Gitpod (now Ona). - Devpod CLI promises to start your devcontainer inside any number of cloud infrastructure. - NEXT FRAGMENT - I'm still building the development version of the application, but also adding in cloud tools that would never go into a production image - NEXT FRAGMENT - LLM Agents have entered the presentation! - Same problem when you have to pause work in one branch to fix a bug in the production branch. - Hassle to either reset the container environment back to the production state, or check out a fresh git repository and set new, non-conflicting settings. - NEXT FRAGMENT - But I found out how to automate that --- ### Definition of a `devcontainer` The definition file is [`.devcontainer/devcontainer.json`](https://github.com/jtmitchell/django-helloworld/blob/main/.devcontainer/devcontainer.json) It has several main sections - building the container - startup commands - custom editor configuration --- ### `devcontainer.json`: Building the container Use Docker Compose to start the background services. ```json "name": "Hello World app", "initializeCommand": ["bash", ".devcontainer/initialize.sh"], "dockerComposeFile": [ "docker-compose.yml", "docker-compose.personal.yml" ], "workspaceFolder": "/workspace", "service": "devcontainer", "remoteUser": "vscode", "features": { "ghcr.io/jsburckhardt/devcontainer-features/just:1": {}, "ghcr.io/nlstn/devcontainer-features/psql:1": {} }, ``` Note: - specify the workspace folder, the **USER** from the Dockerfile, and which service is the home - as the set up got more complex, it got moved into the `initialize.sh` script - the features section is added on each startup, so it can be slow --- ### `devcontainer.json`: Startup command When the container starts it installs Python and the dependencies. ```json "postCreateCommand": "uv venv --clear --no-managed-python ${containerWorkspaceFolder}/.venv && just install", "postStartCommand": "uv sync --locked && uv run pre-commit gc", "mounts": [ "source=precommit-cache,target=/home/vscode/.cache/pre-commit,type=volume", "source=uv-cache,target=/home/vscode/.cache/uv,type=volume" ], ``` Note: - uv creates the venv and installs packages - we also install pre-commit - mount the uv and precommit caches into their own ephemeral volumes --- ### `devcontainer.json`: Custom editor configuration Everyone gets the same initial editor configuration. ```json "customizations": { "vscode": { "extensions": [ "charliermarsh.ruff", "ms-python.python", "ms-python.debugpy" ], "settings": { "python.languageServer": "None", "python.testing.unittestEnabled": false, "python.testing.pytestEnabled": true, "[python]": { "editor.defaultFormatter": "charliermarsh.ruff", "editor.formatOnSave": true, "editor.codeActionsOnSave": { "source.fixAll.ruff": "explicit", "source.organizeImports.ruff": "explicit" } }, "basedpyright.disableLanguageServices": true, "python.analysis.typeCheckingMode": "off", "python.terminal.useEnvFile": true, "python.defaultInterpreterPath": "/workspace/.venv/bin/python" } } } ``` Note: JetBrains and Zed have similar custom sections. - [JetBrains config](https://www.jetbrains.com/help/idea/customizing-devcontainer-json-file.html#copy_git_settings) - [Zed config](https://zed.dev/docs/dev-containers#editing-the-dev-container-configuration) I'm setting up ruff and pytest, and disabling the builtin type checker --- ### Custom `Dockerfile` Define a custom Dockerfile to build the base image. We inherit the default user and home directory from the base image. ```docker ARG UV_VERSION=latest FROM ghcr.io/astral-sh/uv:$UV_VERSION AS uv FROM mcr.microsoft.com/devcontainers/python:3.14 ENV PYTHONDONTWRITEBYTECODE=True \ PYTHONUNBUFFERED=True \ UV_LINK_MODE=copy \ UV_CACHE_DIR=/home/vscode/.cache/uv \ PRE_COMMIT_HOME=/home/vscode/.cache/pre-commit \ PRE_COMMIT_USE_UV=1 \ VIRTUAL_ENV=/workspace/.venv \ PATH=/workspace/.venv/bin:$PATH COPY --from=uv --chown=vscode: /uv /uvx /bin/ # Pre-create mount points owned by vscode so new named volumes inherit ownership RUN mkdir -p /workspace/.venv /home/vscode/.cache/uv /home/vscode/.cache/pre-commit \ && chown -R vscode: /workspace/.venv /home/vscode/.cache ARG AZURE_CLI_VERSION=2.88.0 RUN UV_TOOL_DIR=/opt/uv-tools \ UV_TOOL_BIN_DIR=/usr/local/bin \ UV_COMPILE_BYTECODE=1 \ uv tool install \ --no-cache \ --no-managed-python \ --python /usr/local/bin/python3.14 \ "azure-cli==${AZURE_CLI_VERSION}" ``` Note: By using a custom image, which is built and pushed in the GitHub workflow, I can pre-install all the tools I need. \ This reduces the start up time compared to using the devcontainers **feature** option. Why am I still using features for the **just** and **psql** tools? --- ### Scripting the personal stuff This devcontainer has some extras - [initialize.sh script](https://github.com/jtmitchell/django-helloworld/blob/main/.devcontainer/initialize.sh) - ensures we have the custom files in place - creates dotenv files for the devcontainers - [docker compose personal template](https://github.com/jtmitchell/django-helloworld/blob/main/.devcontainer/docker-compose.personal.template.yml) - gives me the option to override the Dockerfile and install non-standard tools - define personal volume mounts Note: - The non-standard tools and volume mounts are for LLM agents. - I install codex and opencode, and the openspec skill in the Dockerfile. - Then I mount the agent and skill configs from my home directory
### Worktrees and agents This is a recorded demo, which... - Creates three **git worktrees**, one for each feature - Starts a devcontainer for each worktree - Runs an isolated LLM agent inside each container Note: - worktrees are lightweight git checkouts - using an agent skill called openspec - openspec changes in main branch before starting the worktrees - going to use OpenAI Codex, and OpenCode - the demo is dividing the terminal into panes so we can see three tasks at once
### Conclusion - Use **pre-commit**, **uv**, **ruff**, and **bandit** to keep the code "clean" - Use containers to make a production-like environment - Use devcontainers to supply all the tools in a project - Automate the hard stuff with
just
- Allow space for others to customise their environment --- ### Questions? These slides are available online at [talk.maungawhau.net.nz](https://talk.maungawhau.net.nz/posts/devcontainers/) --- ### Workshop notes The source code is at https://github.com/jtmitchell/django-helloworld/ [](https://codespaces.new/jtmitchell/django-helloworld/?ref=main&quickstart=1) - Either clone the code locally and follow the instructions in [README.md](https://github.com/jtmitchell/django-helloworld/blob/main/README.md) - Or [Open in GitHub Codespaces](https://codespaces.new/jtmitchell/django-helloworld/?ref=main&quickstart=1) - Codespaces will take 3 minutes to build the devcontainer when it first starts. - It will also have several annoying VSCode popups to click through - Remember there is a cache on the page view. - Unless you change the cache value, changes can take up to 20 sec to be visible
### Workshop task 1 Login to the Django Admin --- ### Login to the Django Admin - Create a superuser account - `just manage createsuperuser` - Load the Django admin at **`/admin/`** - login with your new username and password - The page views are listed at **`/admin/echo/pageviews/`** - reload the Hello world page, and verify the page view increases
### Workshop task 2 Change the greeting message --- ### Change the greeting message - Edit [home.html](https://github.com/jtmitchell/django-helloworld/blob/main/src/echo/templates/echo/home.html) to change the greeting - also edit [base.html ](https://github.com/jtmitchell/django-helloworld/blob/main/src/templates/base.html)to change the page title - Reload the page
### Workshop task 3 Use a template variable for the greeting message --- ### Use a template variable for the greeting message - Edit [views.py](https://github.com/jtmitchell/django-helloworld/blob/main/src/echo/views.py) to pass a variable in the template context - **`return render(request, "echo/home.html", {"greeting": "Gidday!"})** --- - Edit [home.html](https://github.com/jtmitchell/django-helloworld/blob/main/src/echo/templates/echo/home.html) and [base.html ](https://github.com/jtmitchell/django-helloworld/blob/main/src/templates/base.html) - replace the greeting text with the variable - "**Hello World**" becomes "**`{{ greeting }}`**" - Reload the page
### Workshop task 4 Get the greeting from the database --- ### Get the greeting from the database - Edit [models.py ](https://github.com/jtmitchell/django-helloworld/blob/main/src/echo/models.py)to add a new field to the PageViews model - Under the existing fields `page` and `views`, add a field for `greeting` - **`greeting = models.CharField(default="", blank=False, null=False, max_length=1024)`** --- - Create the database migration, and apply the changes to the database - `just makemigrations` - `just migrate` --- - Navigate to the Django admin page for the view "echo:home" and change the greeting. - Edit [home.html](https://github.com/jtmitchell/django-helloworld/blob/main/src/echo/templates/echo/home.html) and [base.html ](https://github.com/jtmitchell/django-helloworld/blob/main/src/templates/base.html) - replace the greeting text with the variable - "**Hello World**" becomes "**`{{ greeting }}`**" --- Edit [views.py](https://github.com/jtmitchell/django-helloworld/blob/main/src/echo/views.py) to read the database to find the greeting, and pass it in the template context ```python # Create your views here. from typing import TYPE_CHECKING from django.shortcuts import render from django.views.decorators.cache import cache_page from . import models from .decorators import count_page_view if TYPE_CHECKING: from django.http import HttpRequest, HttpResponse @count_page_view @cache_page(10 * 2) def home(request: HttpRequest) -> HttpResponse: """Print hello world.""" match = request.resolver_match page_name: str = match.view_name if match else request.path if page := models.PageViews.objects.filter(page=page_name).first(): greeting = page.greeting or "Hello World" else: greeting = "Hello World" return render(request, "echo/home.html", {"greeting": greeting}) ``` Reload the page
### Links - git - [git-scm.com](https://git-scm.com/) - python - [python.org](https://www.python.org/) - django - [djangoproject.com](https://www.djangoproject.com/) - uv - [docs.astral.sh/uv](https://docs.astral.sh/uv/) - pre-commit - [pre-commit.com](https://pre-commit.com/) - ruff - [docs.astral.sh/ruff/](https://docs.astral.sh/ruff/) - ty - [docs.astral.sh/ty/](https://docs.astral.sh/ty/) - bandit - [bandit.readthedocs.io](https://bandit.readthedocs.io/) - just - [just.systems/man/en/](https://just.systems/man/en/) - direnv - [direnv.net](https://direnv.net/) - docker-compose - [docs.docker.com/compose/](https://docs.docker.com/compose/) - devcontainers - [containers.dev](https://containers.dev/) - vscode - [code.visualstudio.com](https://code.visualstudio.com/) - pycharm - [www.jetbrains.com/pycharm/](https://www.jetbrains.com/pycharm/) - zed - [zed.dev](https://zed.dev/)