Skip to main content

Dev tools and workflow · Intermediate · 18 min

Develop inside a dev container with devcontainer.json

By Padding · Updated 18 Nov 2026
devcontainers CLI 0.91 · Node.js 26 (javascript-node 5-26-trixie image) · Docker on macOS, Windows (WSL 2) or Linux

You will have a Node.js 26 project with a committed devcontainer.json, plus a Compose variant with PostgreSQL 18, that opens the same way in VS Code, from the devcontainers CLI, in GitHub Actions and in Codespaces.

On this page

A dev container is a Docker container that holds your project's toolchain: the right Node.js version, the command-line tools, the editor extensions and the services the code talks to. The recipe lives in .devcontainer/devcontainer.json, committed next to the code. Anyone with Docker can open the project and get the same environment, and so can a CI runner or a cloud machine such as GitHub Codespaces. The file format is an open specification at containers.dev. VS Code, the devcontainers command-line tool and Codespaces all read it.

It is not always worth it. A dev container pays off when a project needs a specific runtime version, extra services such as a database, or native tools that are painful to install on every operating system, and when several people or CI need to agree on all of that. It costs you disk space (one base image is often a gigabyte or more once Features are added), memory for Docker, and on macOS and Windows a Linux virtual machine running in the background plus slower file access through bind mounts. For a solo script that runs on whatever Node.js you have, skip it.

If you work on prepaid mobile data, as many developers across Africa do, the first build is the expensive part: it pulls the base image, the Features and every npm package. Do it once on Wi-Fi. Later starts reuse the cached image and cost almost nothing. Codespaces moves that download to GitHub's network instead of yours.

In this tutorial you build a small Node.js 26 web server, give it a dev container, open it in VS Code, run it headless with the devcontainers CLI 0.91, add PostgreSQL 18 through Docker Compose, and reuse the same configuration in GitHub Actions and Codespaces. The commands are for a shell on macOS, Linux or WSL 2.

Step 1 · Make the demo project and check Docker

First confirm that Docker is running. Every later step needs it:

Bash
docker info --format '{{.ServerVersion}}'

Then create a throwaway project folder with a tiny server, a health function and one test. Nothing here needs Node.js on your computer; the container will supply it.

Bash
mkdir -p ~/devcontainer-demo/test ~/devcontainer-demo/.devcontainer
cd ~/devcontainer-demo
cat > package.json <<'EOF'
{
  "name": "devcontainer-demo",
  "private": true,
  "type": "module",
  "scripts": {
    "start": "node server.js",
    "test": "node --test"
  }
}
EOF
cat > health.js <<'EOF'
export function health() {
  return { ok: true, node: process.version };
}
EOF
cat > server.js <<'EOF'
import http from 'node:http';
import { health } from './health.js';

const port = Number(process.env.PORT ?? 3000);
http
  .createServer((req, res) => {
    res.writeHead(200, { 'content-type': 'application/json' });
    res.end(JSON.stringify(health()));
  })
  .listen(port, '0.0.0.0', () => console.log(`Listening on port ${port}`));
EOF
cat > test/health.test.js <<'EOF'
import { test } from 'node:test';
import assert from 'node:assert/strict';
import { health } from '../health.js';

test('health reports ok on Node.js 26', () => {
  const result = health();
  assert.equal(result.ok, true);
  assert.match(result.node, /^v26\./);
});
EOF
printf 'node_modules/\n' > .gitignore

The test checks the Node.js major version on purpose. It fails on any machine that is not running Node.js 26, which is exactly the drift a dev container prevents.

The server listens on 0.0.0.0 rather than localhost. Inside a container, localhost means the container itself, so a server bound only to it cannot be reached through a forwarded port.

Check it worked

docker info printed a version number such as 29.x rather than an error about the daemon. ls -A ~/devcontainer-demo lists .devcontainer, .gitignore, health.js, package.json, server.js and test.

Step 2 · Write a first devcontainer.json

Create .devcontainer/devcontainer.json. The file is JSON with comments, so you can explain each choice to your teammates in place:

Bash
cat > ~/devcontainer-demo/.devcontainer/devcontainer.json <<'EOF'
{
  // Shown in the editor's status bar and in the CLI output.
  "name": "devcontainer-demo",

  // Microsoft's Node.js dev container image: Node.js 26 on Debian trixie,
  // with git, a non-root "node" user and common shell tools already installed.
  "image": "mcr.microsoft.com/devcontainers/javascript-node:5-26-trixie",

  // Port 3000 inside the container appears as localhost:3000 on your computer.
  "forwardPorts": [3000],

  // Runs once, inside the container, after it is created.
  "postCreateCommand": "npm install"
}
EOF

A few decisions are worth understanding:

  • Pin the image tag. 5-26-trixie fixes the image's own major version (5), the Node.js major (26) and the Debian release. A bare latest would change under you and defeat the point.
  • postCreateCommand runs once. It runs after the container is first created, not on every start, so put dependency installs there. Once your project has a committed package-lock.json, change it to npm ci so every container installs the exact locked versions.
  • forwardPorts is for the editor and Codespaces. VS Code and Codespaces read it and forward the port for you. The command-line tool on its own does not publish ports, which matters in the headless step below.

Check it worked

cat ~/devcontainer-demo/.devcontainer/devcontainer.json shows the four properties name, image, forwardPorts and postCreateCommand. The image line ends in :5-26-trixie, not :latest.

Step 3 · Add Features and editor settings

A Feature is a packaged install script for a tool, published as an image reference and added at build time. You list it under features instead of writing apt install lines. Features keep the base image generic and the extra tools declared in one place.

customizations.vscode holds editor-only settings: extensions to install inside the container and settings that apply there. Other tools ignore this block, so it does no harm in CI.

Replace the file with this fuller version:

Bash
cat > ~/devcontainer-demo/.devcontainer/devcontainer.json <<'EOF'
{
  "name": "devcontainer-demo",
  "image": "mcr.microsoft.com/devcontainers/javascript-node:5-26-trixie",

  // Extra tools, installed when the image is built.
  "features": {
    "ghcr.io/devcontainers/features/github-cli:1": {}
  },

  "forwardPorts": [3000],
  "portsAttributes": {
    "3000": { "label": "Demo server" }
  },

  "postCreateCommand": "npm install",

  "customizations": {
    "vscode": {
      "extensions": ["dbaeumer.vscode-eslint", "esbenp.prettier-vscode"],
      "settings": {
        "editor.formatOnSave": true,
        "editor.defaultFormatter": "esbenp.prettier-vscode"
      }
    }
  }
}
EOF

The :1 after the Feature name is its major version. Like the image tag, it lets you take fixes without surprise breaking changes. Browse the official and community Features at containers.dev/features before writing your own install steps; Go, Python, the AWS CLI, Terraform and many others are there.

Keep personal preferences, such as your theme or font size, out of this file. They belong in your own user settings. The dev container should hold only what the project needs to build, test and look consistent in review.

Check it worked

The file now has a features block naming ghcr.io/devcontainers/features/github-cli:1 and a customizations.vscode block with two extension IDs. Standard JSON checkers reject the comments, so check the shape by eye; the next step catches typos, because VS Code and the CLI both report a syntax error with its line number.

Step 4 · Open the project in VS Code

Install the Dev Containers extension (publisher Microsoft) in VS Code if you have not already. Then:

  1. Open ~/devcontainer-demo in VS Code. A notification offers to reopen the folder in a container. If you miss it, open the Command Palette (F1) and run Dev Containers: Reopen in Container.
  2. Wait for the first build. VS Code pulls the image, installs the GitHub CLI Feature, starts the container and runs npm install. Select show log in the notification to follow it.
  3. Open a terminal in VS Code. It is a shell inside the container, working in /workspaces/devcontainer-demo, as the node user.
  4. Run npm start in that terminal and open http://localhost:3000 in your browser.

Your files are not copied into the container. The project folder is bind-mounted, so an edit in VS Code changes the file on your disk straight away, and Git on your computer sees it.

When you change devcontainer.json later, the running container does not pick it up by itself. Run Dev Containers: Rebuild Container from the Command Palette.

On macOS and Windows, a bind-mounted folder is noticeably slower than a native disk for things like npm install in a large project. If that bites, the VS Code documentation shows how to keep node_modules in a named volume, or you can use Dev Containers: Clone Repository in Container Volume so the whole repository lives inside Docker.

Check it worked

The bottom-left corner of VS Code shows Dev Container: devcontainer-demo. In the container terminal, node --version prints v26. followed by the patch version, and gh --version prints a GitHub CLI version. The browser at http://localhost:3000 shows JSON like {"ok":true,"node":"v26.13.0"}. The Extensions view lists ESLint and Prettier under the container's section, not only under Local.

Step 5 · Run the container headless with the devcontainers CLI

The same file works without an editor. That is how you script it, use it from other editors, and run it in CI. Install the reference CLI with npm, pinned to the version this tutorial uses:

Bash
npm install -g @devcontainers/cli@0.91.0
devcontainer --version

If you use a Node.js version manager, the global install belongs to the Node.js version that is active now. Close VS Code's container window first, so you are not sharing the container while learning the CLI. Then build and start the container from the project folder:

Bash
cd ~/devcontainer-demo
devcontainer up --workspace-folder .

up builds the image if needed, applies the Features, starts the container and runs postCreateCommand. It ends by printing a line of JSON that includes "outcome":"success" and the container ID. Now run commands inside it with exec:

Bash
devcontainer exec --workspace-folder . node --version
devcontainer exec --workspace-folder . npm test

exec runs as the same node user, in the same working folder and with the same environment as VS Code's terminal. To try the server, run it in the background inside the container and fetch from it there, because the CLI does not forward ports:

Bash
devcontainer exec --workspace-folder . sh -c 'node server.js > /tmp/server.log 2>&1 & sleep 1; node -e "fetch(\"http://localhost:3000\").then(r => r.text()).then(console.log)"'

After you change devcontainer.json, recreate the container from scratch:

Bash
devcontainer up --workspace-folder . --remove-existing-container

Check it worked

devcontainer --version prints 0.91.0. devcontainer up ends with JSON containing "outcome":"success". node --version through exec prints v26. and a patch number even if your computer has a different Node.js or none at all. npm test reports pass 1 and fail 0. The fetch command prints {"ok":true,"node":"v26....."}.

Step 6 · Add PostgreSQL with a Compose-based dev container

When the code needs a database, switch the dev container to Docker Compose. Compose runs your workspace container and a PostgreSQL container side by side on a private network, and devcontainer.json names which one you work in. This tutorial uses PostgreSQL 18 to match the rest of the library; PostgreSQL 19 is also out, and the steps are the same with postgres:19.

The database needs a password. It must not be committed, and it must not be typed on the command line where shell history keeps it. Add a small script that creates a private .devcontainer/.env file with a random password the first time, and leaves an existing one alone:

Bash
cd ~/devcontainer-demo
cat > .devcontainer/make-env.sh <<'EOF'
#!/bin/sh
# Creates .devcontainer/.env with a random local database password, once.
set -eu
f=.devcontainer/.env
if [ -f "$f" ]; then exit 0; fi
umask 077
pw="$(od -An -N16 -tx1 /dev/urandom | tr -d ' \n')"
printf 'POSTGRES_PASSWORD=%s\nPGPASSWORD=%s\n' "$pw" "$pw" > "$f"
EOF
chmod 755 .devcontainer/make-env.sh
printf '.devcontainer/.env\n' >> .gitignore

The umask 077 line runs before the file is written, so the file is created readable only by you rather than locked down afterwards. Now the Compose file. The app service uses the same Node.js image and stays alive with sleep infinity so you can work in it. The db service is the official PostgreSQL 18 image with its data in a named volume:

Bash
cat > .devcontainer/compose.yaml <<'EOF'
services:
  app:
    image: mcr.microsoft.com/devcontainers/javascript-node:5-26-trixie
    volumes:
      - ..:/workspaces/devcontainer-demo:cached
    command: sleep infinity
    env_file: .env
    environment:
      PGHOST: db
      PGUSER: postgres
      PGDATABASE: postgres
    depends_on:
      - db

  db:
    image: postgres:18
    env_file: .env
    volumes:
      - pgdata:/var/lib/postgresql

volumes:
  pgdata:
EOF

Paths in compose.yaml are relative to the .devcontainer folder, which is why the project is mounted from ... The database volume is mounted at /var/lib/postgresql, as the PostgreSQL 18 image expects. The database port is not published to your computer at all; only the app container can reach it, by the hostname db.

Replace devcontainer.json with the Compose version. initializeCommand runs the script on the host before the containers start, so a fresh clone, a CI runner or a codespace all get their own .env without anyone typing a password:

Bash
cat > .devcontainer/devcontainer.json <<'EOF'
{
  "name": "devcontainer-demo with PostgreSQL",

  // Runs on the host (or the cloud machine) before the containers start.
  "initializeCommand": "sh .devcontainer/make-env.sh",

  "dockerComposeFile": "compose.yaml",
  "service": "app",
  "workspaceFolder": "/workspaces/devcontainer-demo",

  "features": {
    "ghcr.io/devcontainers/features/github-cli:1": {}
  },

  "forwardPorts": [3000],
  "postCreateCommand": "npm install",

  "customizations": {
    "vscode": {
      "extensions": ["dbaeumer.vscode-eslint", "esbenp.prettier-vscode"],
      "settings": { "editor.formatOnSave": true }
    }
  }
}
EOF

Add the PostgreSQL client library and a script that connects using the PG* variables Compose passed in. pg reads PGHOST, PGUSER, PGPASSWORD and PGDATABASE by itself, so no password appears in the code:

Bash
cat > db-check.js <<'EOF'
import pg from 'pg';

const client = new pg.Client();
await client.connect();
const { rows } = await client.query('select version()');
console.log(rows[0].version);
await client.end();
EOF

The old single-container setup is still running. List your containers and remove the one from the earlier steps; its name is random, so copy the ID from the docker ps output (replace <container-id>):

Bash
docker ps
docker rm -f <container-id>

Then start the Compose version, install pg pinned to the version checked for this tutorial, and run the check:

Bash
devcontainer up --workspace-folder .
devcontainer exec --workspace-folder . npm install pg@8.23.1
devcontainer exec --workspace-folder . node db-check.js

In VS Code, the same change is Dev Containers: Rebuild Container. When you close the window, VS Code stops both Compose containers, because stopCompose is the default shutdown behaviour for Compose-based dev containers.

Check it worked

ls -l ~/devcontainer-demo/.devcontainer/.env shows -rw-------, and git check-ignore -v .devcontainer/.env (once the folder is a Git repository) names the .gitignore rule. node db-check.js prints a line beginning PostgreSQL 18. followed by the patch version and build details. package.json now lists pg under dependencies at 8.23.1 (npm adds a ^ in front by default). npm test through exec still passes.

Step 7 · Use the same configuration in CI and Codespaces

Because the configuration is a file, your CI can run tests in exactly the environment developers use. The devcontainers/ci GitHub Action builds the dev container with the same CLI and runs a command in it. Add a workflow:

Bash
mkdir -p ~/devcontainer-demo/.github/workflows
cat > ~/devcontainer-demo/.github/workflows/test.yml <<'EOF'
name: test
on: [push, pull_request]

jobs:
  test:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v7
      - name: Run the tests in the dev container
        uses: devcontainers/ci@v0.3
        with:
          push: never
          runCmd: npm test
EOF

initializeCommand runs on the runner first, so the runner makes its own throwaway .env and the PostgreSQL service starts with it. postCreateCommand installs the dependencies, then runCmd runs the tests. The action can also build the image once, push it to a registry and reuse it as a cache in later runs; its README shows that setup, which cuts build time on every push.

For Codespaces, push the repository to GitHub and create a codespace from the repository's Code button. Codespaces finds .devcontainer/devcontainer.json, runs initializeCommand on the cloud machine, builds the containers there and opens VS Code in the browser or in your desktop VS Code. The forwarded port 3000 gets a private URL you can open. Codespaces is billed for compute and storage beyond the usage included each month, so stop or delete codespaces you are not using.

Check it worked

After you push, the repository's Actions tab shows the test workflow, and the step "Run the tests in the dev container" logs pass 1 and fail 0. If you try Codespaces, the terminal in the codespace prints v26. for node --version, and node db-check.js prints PostgreSQL 18..

Step 8 · Clean up the demo

The containers, images and the database volume stay on your disk until you remove them. A Compose-based dev container keeps its data in a named volume, so removing the containers alone does not delete the database.

List what the demo created, then remove the containers and the volume by the names docker shows you. The volume name ends in _pgdata and starts with the Compose project name the CLI chose, so copy it from the output (replace <container-id> and <volume-name>):

Bash
docker ps -a
docker rm -f <container-id>
docker volume ls
docker volume rm <volume-name>

Then delete the project folder and, if you no longer want it, the CLI:

Bash
rm -rf ~/devcontainer-demo
npm uninstall -g @devcontainers/cli

Remove the downloaded images with docker image ls and docker image rm <image-id> if you need the disk space back; leave them if you will build another dev container soon, especially on metered data.

Check it worked

docker ps -a no longer lists the demo containers, docker volume ls has no _pgdata volume from the demo, and ls ~/devcontainer-demo reports that the folder does not exist. If you deleted any codespace you created, the Codespaces list on GitHub no longer shows it.

Next steps

Need this done for you?

Padding does this work for growing companies, from the first diagnosis to a system that keeps working.

Platform Engineering

Get new tutorials

New tutorials, about twice a month.