Skip to content
Tutorials Center
My learning

Topics

Lesson 97 of 111 ยท Orchestration Basics

Dev Containers and Remote Development

Use containers as your development environment: devcontainer.json, building a dev image, bind-mounted workspaces, Compose-based setups, and VS Code or Codespaces.

"It works on my machine" is the oldest complaint in software. You have already seen one cure for production: ship an image, so the app runs the same everywhere. A dev container applies the same cure to the development environment. Instead of asking every new teammate to install the right Python, Node, database, compilers and linters (and then debug their differences for a day), you describe the environment once, in the repository, and your editor runs it in a container. You open the project and everything is already there.

This lesson explains what a dev container is, how devcontainer.json describes it, what a tool like VS Code actually does with it, how to add a database through Compose, and when dev containers help or get in the way. The container parts were run with plain Docker, which is all the technology underneath. The editor parts (VS Code, Codespaces) are read-only examples, because no editor was running here.

What a dev container is

A dev container is an ordinary Docker container used as a workspace:

  • Its image contains the toolchain: language runtime, compiler, package manager, git, linters, CLI tools.
  • Your source code is bind-mounted into it (see Bind Mounts), so you edit files with an editor and the files are really on your disk.
  • The container runs a long-lived idle process (like sleep infinity), and your tools run inside it: terminals, the debugger, the test runner, even editor extensions such as language servers.
  • It runs as a non-root user whose UID matches yours, so files you create are not owned by root.
TEXT
  your laptop                                     the container
 +-------------------------------+        +----------------------------------+
 | editor UI (VS Code)           | <----> | editor server + extensions       |
 | project folder  <==== bind mount ====> | /workspaces/proj                 |
 | browser (localhost:8000) <----- port forward -- app on port 8000          |
 +-------------------------------+        | python, git, pip, linters ...    |
                                          +----------------------------------+

The idea is open: the Development Containers specification (containers.dev) defines the devcontainer.json format, and several tools implement it: VS Code (the Dev Containers extension), JetBrains IDEs, GitHub Codespaces, the devcontainer command-line tool and others.

Building one by hand

Before looking at the JSON, build the pieces yourself, so you know there is no magic. This is a project folder with a small Python program and a .devcontainer/Dockerfile:

TEXT
proj/
  app.py
  requirements.txt
  .devcontainer/
    Dockerfile
    devcontainer.json

The Dockerfile creates a normal user and installs a few tools (this one was built for real):

DOCKERFILE
FROM python:3.13-slim

ARG USERNAME=vscode
ARG USER_UID=1000
ARG USER_GID=1000

RUN apt-get update \
    && apt-get install -y --no-install-recommends git curl \
    && rm -rf /var/lib/apt/lists/* \
    && groupadd --gid $USER_GID $USERNAME \
    && useradd --uid $USER_UID --gid $USER_GID -m -s /bin/bash $USERNAME

USER $USERNAME

Everything here is covered in earlier lessons: RUN with cleanup (FROM and RUN), ARG for values (ENV and ARG) and a non-root USER (WORKDIR, USER, EXPOSE and LABEL). Build it and start an idle container with the project mounted at /workspaces/proj, which is what a dev container tool does automatically:

CONSOLE
$ docker build -t dev-image -f .devcontainer/Dockerfile .
$ docker images dev-image --format '{{.Size}}'
319MB
$ docker run -d --name devbox -v "$PWD:/workspaces/proj" -w /workspaces/proj \
    --entrypoint sh dev-image -c 'while sleep 1000; do :; done'

(The size is the content size reported by this machine, not a promise. On Git Bash for Windows, pass the host path in Windows form, for example $(pwd -W), or the mount stays empty.) Now run commands in the box, just as the editor's terminal would:

CONSOLE
$ docker exec devbox id
uid=1000(vscode) gid=1000(vscode) groups=1000(vscode)
$ docker exec devbox python app.py
hello from the dev container
$ docker exec devbox git --version
git version 2.47.3
$ docker exec devbox python -c "import sys; print(sys.version.split()[0])"
3.13.17

The Python and Git versions come from the image, not from your laptop. Files created inside appear on the host, because the folder is shared:

CONSOLE
$ docker exec devbox sh -c 'echo made-in-container > note.txt; ls -l note.txt'
-rw-r--r-- 1 vscode vscode 18 Oct 23 15:25 note.txt
$ ls
app.py  note.txt  requirements.txt
$ cat note.txt
made-in-container

That is the whole mechanism: an image with tools, a bind mount, an idle process and a non-root user. A dev container tool automates it and wires an editor into it.

The useradd --uid 1000 line matters on Linux. If your own user id on the host is different, files created in the container are owned by a user you are not, and permission errors follow. Dev container tools can update the container user's UID to match yours (updateRemoteUserUID, on by default on Linux). On Docker Desktop for macOS and Windows, the file sharing layer hides most of this. See Users and Permissions.

devcontainer.json

The file .devcontainer/devcontainer.json (or .devcontainer.json in the project root) tells a tool how to create and use the container. It is JSON with comments allowed. A realistic minimal file for the Dockerfile above (a read-only example, since it needs an editor to be interpreted):

JSON
{
  "name": "Python dev",
  "build": {
    "dockerfile": "Dockerfile",
    "context": ".."
  },
  "remoteUser": "vscode",
  "forwardPorts": [8000],
  "postCreateCommand": "pip install --user -r requirements.txt",
  "customizations": {
    "vscode": {
      "extensions": ["ms-python.python"],
      "settings": { "python.defaultInterpreterPath": "/usr/local/bin/python" }
    }
  }
}

Line by line:

  • name is the label shown in the editor.
  • build points to a Dockerfile, relative to the .devcontainer folder. context: ".." makes the project root the build context. Instead of build you can use "image": "mcr.microsoft.com/devcontainers/python:3.13" to start from a prebuilt development image, which saves a Dockerfile and build time.
  • remoteUser is the user your terminals and tools run as. It is not root, which is good practice for the same reasons as in production.
  • forwardPorts makes localhost:8000 on your laptop reach port 8000 inside the container, so you can open the web app in your normal browser.
  • postCreateCommand runs once after the container is created, the right place for dependency installation. Related hooks are onCreateCommand, updateContentCommand, postStartCommand (every start) and postAttachCommand. Commands can be strings, arrays or objects of parallel commands.
  • customizations.vscode lists extensions and settings that are installed in the container, so everybody on the team gets the same linter version and the same editor configuration.

Other keys you will use: containerEnv and remoteEnv for environment variables, mounts for extra mounts (for example a named volume for a package cache), runArgs for extra docker run flags, capAdd and securityOpt when a tool needs them, and workspaceFolder / workspaceMount to change where the project appears (the default is /workspaces/<project folder name>).

Features

Features are small installable units that add tools to any base image without you writing the RUN commands. A feature is referenced by an OCI image reference, with options:

JSON
{
  "image": "mcr.microsoft.com/devcontainers/base:debian",
  "features": {
    "ghcr.io/devcontainers/features/node:1": { "version": "lts" },
    "ghcr.io/devcontainers/features/docker-outside-of-docker:1": {}
  }
}

(Read-only example.) This adds Node.js to a Debian base image and gives the container access to the host's Docker daemon. The last feature is an instance of the socket pattern from Docker in Docker and Socket Access: handy on your own laptop, wrong for a shared server. Features are built into an image layer when the container is created, so they cost time on first start but not afterward.

Adding services with Compose

Real projects need a database or a cache next to the code. A dev container can be backed by a Compose file instead of a single image, so the workspace container joins a network with the other services. This file was brought up for real with docker compose up -d --build:

YAML
services:
  app:
    build:
      context: ..
      dockerfile: .devcontainer/Dockerfile
    volumes:
      - ..:/workspaces/proj:cached
    command: sleep infinity
    depends_on:
      db:
        condition: service_healthy
  db:
    image: postgres:17-alpine
    environment:
      POSTGRES_PASSWORD: dev-only-password
    volumes:
      - dbdata:/var/lib/postgresql/data
    healthcheck:
      test: ["CMD-SHELL", "pg_isready -U postgres"]
      interval: 5s
      timeout: 3s
      retries: 10
volumes:
  dbdata:
CONSOLE
$ docker compose up -d --build
 Container proj-db-1 Starting
 Container proj-db-1 Started
 Container proj-db-1 Waiting
 Container proj-db-1 Healthy
 Container proj-app-1 Starting
 Container proj-app-1 Started
$ docker compose ps --format 'table {{.Service}}\t{{.Status}}'
SERVICE   STATUS
app       Up 1 second
db        Up 7 seconds (healthy)
$ docker compose exec app sh -c 'id -un; python -c "print(1+1)"'
vscode
2

The app container waits until the database reports healthy (Startup Order and Health), idles with sleep infinity, and runs as the Dockerfile's vscode user. Code in the workspace reaches the database at the host name db, as described in Containers Talking to Each Other. The password is a development placeholder; never put real secrets in a file you commit.

The JSON then references the Compose file and names the service the editor should attach to (read-only example):

JSON
{
  "name": "App with Postgres",
  "dockerComposeFile": "compose.yaml",
  "service": "app",
  "workspaceFolder": "/workspaces/proj",
  "shutdownAction": "stopCompose",
  "forwardPorts": [8000, 5432]
}

shutdownAction: stopCompose stops the whole stack when you close the editor.

VS Code, JetBrains and Codespaces

With the VS Code Dev Containers extension installed (a read-only description of the workflow):

  1. Open the project folder and choose "Reopen in Container" (or run the command Dev Containers: Reopen in Container).
  2. The extension builds the image from devcontainer.json, starts the container, installs a small VS Code Server inside it, installs your listed extensions there, runs postCreateCommand and attaches the window.
  3. From then on, the integrated terminal, debugger, tests and language servers all run inside the container. The window looks like normal VS Code, and the lower left corner shows the container name.

The first start takes a few minutes. Later starts reuse the container or at least the cached image layers. If you change the Dockerfile or the JSON, use "Rebuild Container".

GitHub Codespaces reads the same devcontainer.json but runs the container in the cloud, on a virtual machine that GitHub provides, and shows the editor in your browser or in a desktop VS Code. A new contributor can click a button and have a working environment in a couple of minutes without installing anything. Costs and quotas are the provider's business, so check them before you roll it out to a team. JetBrains IDEs support dev containers through their remote development features, and the devcontainer CLI (devcontainer up, devcontainer exec) lets you use the same definition from scripts and CI without any editor.

When dev containers help, and when they do not

They help when:

  • The project has many tools or exact versions that are painful to install locally.
  • New people join often, or you run workshops and want identical environments.
  • You develop Linux-targeted software on Windows or macOS: the container is a Linux environment.
  • You want your dev and CI environments to be the same image. CI can run devcontainer or just reuse the Dockerfile.
  • You want to keep a dirty toolchain off your main system, for example when you work on several projects with conflicting versions.

They get in the way when:

  • File access through a bind mount is slow on macOS and Windows for projects with huge node_modules or build output. Keep those directories in named volumes, or clone the repository inside a volume.
  • You need GUI apps, GPUs, USB devices or special kernel features, which require extra configuration.
  • The team does not use an editor with support for dev containers, or the machine is too small to run a container next to an IDE.
  • You treat the container as persistent: remember that the container's own filesystem is disposable. Anything outside the mounted folder and your named volumes (installed packages, shell history, tool settings) is lost on rebuild unless you put it in the image, a feature, a postCreateCommand or a volume (Container Storage).

Keep the dev image separate from the production image. The dev image has compilers, debuggers and git; the production image should be small and minimal (Multi-Stage Builds). A multi-stage Dockerfile with a dev target (build.target in devcontainer.json) can share a base between the two.

Cleaning up

When you finish experimenting, remove what you created:

Terminal
docker rm -f devbox
docker rmi dev-image
docker compose down -v

down -v also removes the named volume with the database, which is what you want for a throwaway environment and exactly what you do not want for data you care about.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What is the basic mechanism of a dev container?

    A dev container is an ordinary container. Tools run in it while the source files stay on your disk through a bind mount.
  2. 2. Where should you put dependency installation that must run once after the container is created?

    postCreateCommand runs after the container is created. forwardPorts only maps ports, and remoteUser selects the user.
  3. 3. What does forwardPorts: [8000] do?

    The tool forwards the port to your local machine so you can open the app in your normal browser.
  4. 4. Why is it a good idea for the dev container to run as a non-root user whose UID matches yours?

    With root, files created through the bind mount can end up owned by root on the host. A matching non-root user avoids that.
  5. 5. Which is the right way to keep a PostgreSQL database next to your workspace in a dev container?

    A Compose-based dev container joins the workspace and the database on one network with a healthcheck, and the service name serves as the host name.

Summary

  • A dev container is a normal container used as a workspace: the toolchain lives in the image, the source is bind-mounted, an idle process keeps it alive and a non-root user runs the tools.
  • devcontainer.json (the open Development Containers spec) describes the image or Dockerfile, ports to forward, lifecycle commands, environment, editor extensions and Features.
  • A Compose-based setup adds databases and caches next to the workspace container, with healthchecks and service names for networking.
  • VS Code (Dev Containers extension), JetBrains, the devcontainer CLI and GitHub Codespaces all read the same file; Codespaces runs it in the cloud.
  • Watch for slow bind mounts on macOS and Windows, UID mismatches on Linux, and lost state when you rebuild; keep dev and production images separate.

Next: Project: Serve a Static Site