# Docker Basics: Containers, Networks, Volumes and Compose

> A Docker basics cheat sheet: docker run, ports, env vars, exec, networks, volumes, Dockerfiles, layer caching, multi stage builds and Docker Compose.

Author: Saksham Malhotra
Published: 2026-10-21
Canonical: https://sakshambuilds.dev/writing/docker-basics

I was revising Docker concepts and realised it'd be better to have them written down somewhere. So why not make it an article on my portfolio :)

## TL;DR

- `docker run` uses the local image if it exists, otherwise pulls it from Docker Hub.
- `-p host:container` maps ports. `-e KEY=value` sets env vars.
- `docker exec -it <name> bash` opens a shell in a running container.
- Containers on a user defined bridge network reach each other by name.
- Volumes keep data after the container is removed.
- In a Dockerfile, order matters: dependencies first, code last.
- Multi stage builds are stages of one image build, not multiple containers.
- `docker compose up -d` / `docker compose down` run and tear down the stack.

## What happens when you run `docker run`?

Docker checks for the image locally. If it's there, it starts a container from it. If not, it pulls it from Docker Hub first.

```bash
docker run -it -p 8080:80 nginx:1.27-alpine
```

An image is the blueprint, a container is a running instance of it. One image, any number of containers.

## How does port mapping work in Docker?

The format is `-p <host_port>:<container_port>`.

```bash
docker run -it -p 8080:80 nginx:1.27-alpine
```

nginx listens on 80 inside the container. The host exposes it on 8080, so `http://localhost:8080` reaches it.

Repeat `-p` for multiple ports:

```bash
docker run -it -p 8080:80 -p 8443:443 nginx:1.27-alpine
```

## How do you pass environment variables to a container?

Repeat `-e` for each variable:

```bash
docker run -it -e APP_ENV=development -e LOG_LEVEL=debug notes-api:1.0
```

## How do you list, start and stop containers?

```bash
docker container ls        # running containers
docker container ls -a     # all containers, including stopped
docker start notes-api     # start an existing container
docker stop notes-api      # stop a running container
```

`start` and `stop` act on existing containers. `docker run` always creates a new one.

Name a container with `--name`, and run it in the background with `-d`:

```bash
docker run -d --name notes-api -p 3000:3000 notes-api:1.0
```

## How do you run commands inside a running container?

```bash
docker exec notes-api ls           # one off command
docker exec -it notes-api bash     # interactive shell
```

`-i` keeps stdin open, `-t` allocates a terminal. Alpine based images usually have no bash, so use `sh` there.

## How do Docker containers talk to each other?

Create a network and attach containers to it:

```bash
docker network create -d bridge dev-net
docker run -it --network=dev-net --name playground ubuntu:24.04
```

On a user defined bridge network, containers resolve each other by name, for example `postgres-db:5432`. The default bridge network doesn't provide name resolution.

Network types:

- **bridge:** default. Private network on the host, ports published with `-p`.
- **host:** shares the host's network stack, no port mapping (Linux).
- **none:** no networking.

## How do you inspect a container or a network?

```bash
docker inspect notes-api         # full container config, including networks and IP
docker network inspect dev-net   # the network and every container on it
```

## How do Docker volumes work?

Data written inside a container is lost when the container is removed. Volumes store it outside.

Bind mount a host path:

```bash
docker run -it -v ./data:/app/data --name notes-api notes-api:1.0
```

Or use a named volume managed by Docker.

## How do you mount a volume created with `docker volume create`?

Create the volume, then pass its name to `-v` when you run a container. The format is `-v <volume_name>:<path_inside_container>`:

```bash
docker volume create notes-data
docker run -d -v notes-data:/var/lib/postgresql/data --name postgres-db postgres:17
```

The volume attaches to the container, not the image. Here Postgres writes its data to `/var/lib/postgresql/data`, which is stored in `notes-data`. Remove the container, run a new one with the same `-v`, and the data is still there.

The same mount with the longer `--mount` syntax:

```bash
docker run -d --mount source=notes-data,target=/var/lib/postgresql/data --name postgres-db postgres:17
```

Check it:

```bash
docker volume ls                 # list volumes
docker volume inspect notes-data # where it lives on the host
docker inspect postgres-db       # see it under "Mounts"
```

If the name after `-v` doesn't exist yet, Docker creates the volume for you. If it starts with `/` or `./`, Docker treats it as a host path (a bind mount) instead.

## How do you write a Dockerfile?

- `FROM <base_img>`: base image.
- `WORKDIR /app`: working directory for the instructions after it.
- `COPY <src> <dest>`: copy files into the image.
- `RUN <command>`: run a command at build time.
- `ENTRYPOINT ["<a>", "<b>"]`: command run when the container starts.

For larger projects use `WORKDIR /app` with `COPY . .`, and add a `.dockerignore` so build output and secrets stay out of the image:

```text
node_modules
.git
.env
dist
```

`ENTRYPOINT` in exec form is a JSON array, so it needs double quotes: `["node", "main.js"]`.

## Why does order matter in Docker layer caching?

Each instruction is a cached layer. On rebuild, Docker reuses layers up to the first one that changed and rebuilds everything after it.

Slow, because any code change invalidates `npm ci`:

```dockerfile
FROM node:22-alpine
WORKDIR /app
COPY . .
RUN npm ci
ENTRYPOINT ["node", "src/main.js"]
```

Fast, because `npm ci` only reruns when the lockfile changes:

```dockerfile
FROM node:22-alpine
WORKDIR /app
COPY package.json package-lock.json ./
RUN npm ci
COPY . .
ENTRYPOINT ["node", "src/main.js"]
```

Put what changes least at the top and what changes most at the bottom.

## What are multi stage builds in Docker?

Multiple stages during one image build, not multiple containers. Build in a full image, copy only the output into a small one:

```dockerfile
FROM node:22 AS build
WORKDIR /app
COPY package.json package-lock.json ./
RUN npm ci
COPY . .
RUN npm run build

FROM node:22-alpine AS runner
WORKDIR /app
COPY --from=build /app/dist ./dist
COPY --from=build /app/node_modules ./node_modules
ENTRYPOINT ["node", "dist/main.js"]
```

The final image has no build tools or source, so it's smaller.

## How does Docker Compose work?

Define the services in `compose.yaml`:

```yaml
services:
  api:
    build: .
    ports:
      - "3000:3000"
    environment:
      MONGO_URL: mongodb://mongo:27017/notes
    depends_on:
      - mongo

  mongo:
    image: mongo:7
    volumes:
      - mongo-data:/data/db

volumes:
  mongo-data:
```

```bash
docker compose up -d   # create and start all services
docker compose down    # stop and remove containers and the network
```

`build: .` builds the API from the Dockerfile in the current folder. Compose puts the services on one network, so the API reaches the database by service name (`mongo:27017`). `depends_on` starts `mongo` before `api`, but doesn't wait for it to be ready. The top level `version` key is obsolete and can be left out. `down` keeps named volumes unless you pass `-v`.

## Docker basics cheat sheet

| Task | Command |
|---|---|
| Run with a port | `docker run -it -p 8080:80 nginx:1.27-alpine` |
| Run detached with a name | `docker run -d --name notes-api -p 3000:3000 notes-api:1.0` |
| Env vars | `docker run -e KEY=value -e OTHER=value notes-api:1.0` |
| List running / all | `docker container ls` / `docker container ls -a` |
| Start / stop | `docker start notes-api` / `docker stop notes-api` |
| Run a command | `docker exec notes-api ls` |
| Shell | `docker exec -it notes-api bash` (or `sh`) |
| Create a network | `docker network create -d bridge dev-net` |
| Run on a network | `docker run -it --network=dev-net --name playground ubuntu:24.04` |
| Inspect | `docker inspect notes-api` / `docker network inspect dev-net` |
| Bind mount | `docker run -v ./data:/app/data notes-api:1.0` |
| Named volume | `docker volume create notes-data` |
| Mount a named volume | `docker run -v notes-data:/var/lib/postgresql/data postgres:17` |
| Compose up / down | `docker compose up -d` / `docker compose down` |
