Skip to content
Velloreth
Developer Tools 7 min read

Docker Basics: Images, Containers and Volumes

Docker packages an application with its dependencies. Learn images, containers, volumes, and the commands you actually use.

By

Images and containers

An image is a read-only template: a filesystem plus metadata such as the default command and exposed ports.

A container is a running instance of an image, with a thin writable layer on top.

docker run nginx

This pulls the nginx image if it is not present, creates a container, and starts it.

The relationship: one image, many containers. Each container has its own writable layer, so changes in one do not affect another.

The core commands

Run a container:

docker run nginx
docker run -d nginx              # detached
docker run -p 8080:80 nginx      # map port 8080 to 80
docker run --name web nginx      # name it
docker run -it ubuntu bash       # interactive shell
docker run --rm alpine echo hi   # remove when it exits

List containers:

docker ps        # running
docker ps -a     # all, including stopped

Stop and remove:

docker stop web
docker rm web
docker rm -f web   # force

List and remove images:

docker images
docker rmi nginx
docker image prune   # remove unused

Logs and exec:

docker logs web
docker logs -f web          # follow
docker exec -it web bash    # shell into a running container

Inspect:

docker inspect web
docker stats

The Dockerfile

A Dockerfile describes how to build an image.

FROM node:20-alpine

WORKDIR /app

COPY package*.json ./
RUN npm ci --omit=dev

COPY . .

EXPOSE 3000
CMD ["node", "server.js"]

Each instruction creates a layer. Layers are cached, so a rebuild reuses unchanged layers.

Order matters for caching. The COPY package*.json and RUN npm ci come before COPY . ., so a change to the source does not invalidate the dependency install. This is the single most important Dockerfile optimisation.

Build it:

docker build -t myapp .
docker build -t myapp:1.0 .

Volumes

A container’s writable layer is removed with the container. Data that must survive needs a volume.

Create and use a volume:

docker volume create pgdata
docker run -v pgdata:/var/lib/postgresql/data postgres

List and inspect:

docker volume ls
docker volume inspect pgdata

Bind mount (maps a host path):

docker run -v $(pwd)/src:/app/src node

Bind mounts are for development, because edits on the host appear immediately in the container. Volumes are for data that must persist.

Anonymous volumes are created when you use -v /path without a name. They are easy to lose track of; prefer named volumes.

Ports and networking

docker run -p 8080:80 nginx

The format is host:container. Port 8080 on the host maps to port 80 in the container.

Expose without publishing:

EXPOSE 3000

EXPOSE documents the port but does not publish it. You still need -p to reach it from the host.

Container-to-container. Containers on the same user-defined network can reach each other by name.

docker network create app
docker run -d --network app --name db postgres
docker run -d --network app --name api myapi
# the api container can reach db at hostname "db"

Environment variables

docker run -e NODE_ENV=production -e PORT=3000 myapp

From a file:

docker run --env-file .env myapp

Note that --env-file does not support comments or quoting in older versions, which is a common surprise.

Multi-stage builds

A multi-stage build uses one stage to build and another to run, so build tools do not end up in the final image.

# Build stage
FROM node:20-alpine AS build
WORKDIR /app
COPY package*.json ./
RUN npm ci
COPY . .
RUN npm run build

# Runtime stage
FROM node:20-alpine
WORKDIR /app
COPY package*.json ./
RUN npm ci --omit=dev
COPY --from=build /app/dist ./dist
CMD ["node", "dist/server.js"]

The final image contains only the runtime dependencies and the built output. A Node image that would be 1GB can drop to under 200MB.

Keeping images small

Use a slim base. node:20-alpine is far smaller than node:20.

Clean up in the same layer. A RUN that installs and removes in one instruction does not leave the removed files in a layer.

RUN apt-get update && apt-get install -y --no-install-recommends curl \
    && rm -rf /var/lib/apt/lists/*

Use a .dockerignore. It excludes files from the build context, which speeds up the build and prevents secrets from being copied.

node_modules
.git
.env
dist

Combine related RUN instructions. Each RUN is a layer, and layers add up.

Containers are not virtual machines

A container is an isolated process, not a virtual machine. It shares the host kernel, which is why it starts in milliseconds and uses little memory.

The implications:

  • The kernel is shared, so a container cannot run a different OS kernel.
  • Isolation is weaker than a VM, though namespaces and cgroups provide a good boundary.
  • Startup is fast, which makes containers suitable for short-lived tasks.

Common mistakes

Losing data on restart. The data is in the container’s writable layer, which is removed with the container. Use a volume.

A huge image. Usually a heavy base image, build tools left in the final image, or a package manager cache that was not cleaned. Use a slim base, a multi-stage build, and clean up in the same layer.

A slow build. The layer cache is being invalidated. Copy the dependency manifest first, install, then copy the source.

A container that exits immediately. The main process finished. A container lives as long as its PID 1 process, so a command that returns ends the container.

Port already in use. Another container or process holds the port. Use docker ps and lsof -i :PORT to find it.

Changes not appearing. A bind mount is not configured, or the path is wrong. Check with docker inspect and the Mounts section.

Secrets in the image. A COPY . . that includes a .env file bakes the secrets into a layer, where they remain even if a later layer deletes the file. Use a .dockerignore.

Cleaning up

Docker accumulates stopped containers, unused images, and dangling volumes.

docker system df              # see what is using space
docker container prune        # remove stopped containers
docker image prune            # remove unused images
docker image prune -a         # remove all unused images
docker volume prune           # remove unused volumes
docker system prune -a        # remove everything unused

docker system prune -a removes all unused images, which means the next build re-downloads the base. It is a useful reset, but it is not free.

Dangling volumes are the ones with no container attached. They are easy to accumulate and can hold a surprising amount of data.

Practical guidance

  • Order the Dockerfile for caching — dependencies before source.
  • Use a multi-stage build to keep the final image small.
  • Use a .dockerignore to exclude node_modules and .git.
  • Use volumes for data that must persist.
  • Use bind mounts for development.
  • Use a slim base image.
  • Clean up in the same layer as the install.
  • Use --rm for one-off containers.

For the related guides, see docker-compose-guide and dockerfile-best-practices. For the broader context, environment-variables-explained and kubernetes-basics.

Quotable summary

An image is a read-only template and a container is a running instance of an image with a writable layer on top, so you can run many containers from one image. A Dockerfile describes how to build an image, and each instruction creates a layer that is cached, which is why the instructions that change least belong near the top. Volumes persist data outside the container’s writable layer, so it survives the container being removed, which is why databases use them. Containers are isolated processes rather than virtual machines, so they share the host kernel and start in milliseconds. Use a multi-stage build and a slim base image to keep the final image small, and a .dockerignore to exclude node_modules and .git from the build context.

Frequently asked questions

What is the difference between an image and a container?
An image is a read-only template containing the filesystem and metadata. A container is a running instance of an image, with a thin writable layer on top. You can run many containers from one image.
What is a Docker volume?
A volume is storage managed by Docker that lives outside the container's writable layer. Data in a volume survives the container being stopped or removed, which is why databases use them.
Why is my container losing data when it restarts?
Because the data is in the container's writable layer, which is removed with the container. Use a volume or a bind mount to persist it.
What is the difference between a volume and a bind mount?
A volume is managed by Docker and stored in Docker's own directory. A bind mount maps a host path directly into the container, which is useful for development because edits appear immediately.
How do I see what is running?
Use docker ps for running containers and docker ps -a for all containers including stopped ones. docker images lists the images on the host.
Why is my image so large?
Common causes are a base image that is too heavy, build tools left in the final image, and package manager caches not being cleaned. Use a slim base, a multi-stage build, and clean up in the same layer.