Docker
Introduction
Docker is an open platform for building, shipping, and running distributed applications. It uses OS-level virtualization to deliver software in packages called containers — standardized, executable units that combine application code with the operating system libraries, dependencies, and configuration required to run that code in any environment.
The core promise is consistency. A container bundles the application and everything it needs, so the same artifact behaves identically in development, test, and production. This eliminates the most common class of deployment failure, the one that begins with "but it works on my machine."
Conceptually:
Base Image (Ubuntu / JDK / Tomcat)
+ Configuration and dependencies
+ Application code
= Docker Image -> run -> Container
Docker separates the application from the infrastructure it runs on. It is lightweight because it requires no hypervisor — containers execute directly against the host machine's kernel.
Why Containers
Application deployment has passed through three generations:
| Era | Model | Stack |
|---|---|---|
| 1990s | Traditional | Hardware → OS → Libraries → App |
| 2000s | Virtualized | Hardware → OS → Hypervisor → Guest OS per VM → App |
| 2013 onward | Containerized | Hardware → OS → Container runtime → App |
Each generation reduced the amount of duplicated operating system beneath each application. A virtual machine carries an entire guest OS; a container shares the host kernel and carries only what the application itself needs.
Developers care because containers:
- Create ready-to-run packaged applications quickly, at low deployment cost
- Automate testing, integration, and packaging
- Remove platform compatibility problems between environments
- Suit next-generation application styles, particularly microservices
Operations cares because containers:
- Improve the speed, frequency, and reliability of releases
- Make the application lifecycle consistent and repeatable — configure once, run many times
- Eliminate environment drift between development, test, and production
- Improve production resiliency and allow scaling out and in on demand
Virtual Machines vs Containers
| Virtual Machine | Container |
|---|---|
| Heavyweight | Lightweight |
| Limited performance | Near-native performance |
| Each VM runs its own full OS | All containers share the host OS kernel |
| Hardware-level virtualization | OS-level virtualization |
| Startup measured in minutes | Startup measured in milliseconds |
| Pre-allocates its memory allowance | Requires far less memory |
| Fully isolated, therefore more secure | Process-level isolation, potentially less secure |
The security row deserves emphasis. Containers isolate processes, not hardware. Because every container on a host shares that host's kernel, a kernel-level vulnerability has a wider blast radius than it would across virtual machines. This is a trade-off accepted in exchange for density and speed, not a problem that has been solved.
Docker Architecture
Docker runs on a client-server model. The client may talk to the Docker host locally or remotely. There are three major components:
Docker Client — the command-line interface through which you issue instructions. The client makes API calls to the daemon; it does no container work itself.
Docker Daemon (Docker Engine) — the process that actually executes those instructions, whether pulling an image, building an image, or running a container. It manages containers, local images, networks, and volumes.
Docker Registry — the store for images. The default public registry is Docker Hub. You can push your own images there as public or private repositories, or run a private registry such as Nexus, JFrog Artifactory, Amazon ECR, or Google Artifact Registry.
The resolution order matters in practice: when you run an image, the daemon first looks in the local image cache, and only if it is absent does it download from the configured registry.
Installation and Verification
Download Docker Desktop for your operating system from docs.docker.com/engine/install.
| Platform | Requirement |
|---|---|
| macOS | Docker Desktop (Intel or Apple Silicon build) |
| Windows | Windows 10/11 64-bit; virtualization (WSL 2 or Hyper-V) enabled |
| Linux | Docker Engine from the distribution or Docker's own apt/yum repository |
Verify the installation:
docker --version # client version
docker version # client and server (daemon) detail
docker info # system-wide information; confirms the daemon is reachable
docker compose version # Compose v2, bundled with modern Docker
If docker version reports a client but no server, the daemon is not running. On Linux,
systemctl status docker will confirm.
Installing on an Ubuntu server
For a cloud VM such as an EC2 instance running Ubuntu Server:
sudo apt update
sudo apt install docker.io
sudo docker version
# add your user to the docker group so sudo is no longer needed
sudo usermod -a -G docker ubuntu
exit
Log out and back in — or restart the shell — for the group change to take effect. After
reconnecting, docker version should work without sudo.
Adding a user to the
dockergroup grants effective root on the host, because that user can mount the host filesystem into a privileged container. Treat membership of this group as equivalent to sudo access.
Core Concepts
Dockerfile
A plain text file describing the steps required to build an image. It uses a small domain-specific language of instructions. The daemon processes these instructions from the top down, so their order matters — both for correctness and for layer caching. The Dockerfile is effectively the source code of the image.
Image
A lightweight, standalone, executable package containing everything needed to run a piece of software: the code, a runtime, libraries, environment variables, and configuration files. Images are read-only templates, built in layers, where each instruction in the Dockerfile produces a layer. Layers are shared between images, which is why pulling a second image based on the same parent is fast.
Container
A runtime instance of an image — what the image becomes in memory when executed. A container runs isolated from the host by default, accessing host files and ports only where explicitly configured. Many containers can run from one image, all sharing the same behaviour, which is what makes horizontal scaling straightforward.
Volume
A specially designated directory used to store data outside the container's own writable layer.
Volumes are created and managed by Docker and, on Linux, live under /var/lib/docker/volumes/.
They exist because data written inside a container does not survive the container's removal.
Registry
A service that stores and distributes images, enabling sharing between machines, teams, and CI pipelines.
The Docker Flow
Dockerfile --build--> Image --run--> Container
The image is assembled in layers:
Application code
Software / dependencies
Container base OS
A complete cycle:
# build an image from the Dockerfile in the current directory
docker build -t dockerhandson/java-web-app:1.0 .
# run a container from that image, detached, with a port mapping
docker run -d --name javaapp -p 8080:8080 dockerhandson/java-web-app:1.0
The trailing . is the build context — the directory Docker sends to the daemon and in which
it looks for the Dockerfile. dockerhandson is the repository namespace, typically your Docker Hub
username.
Image Commands
# list locally stored images
docker images
docker image ls
docker images -q # IDs only
docker images <image-name> # information about one image
# search Docker Hub
docker search puppet
docker search --filter=stars=10 puppet
docker search --no-trunc puppet
# pull an image
docker pull ubuntu # defaults to the :latest tag
docker pull ubuntu:16.04 # a specific tag
# build
docker build -t <image-name>:<tag> .
docker build -t mongodbimage:1.0 .
docker build -f /path/to/Dockerfile . # Dockerfile at a non-default path
# inspect image history, layer by layer
docker history <image-name>:<tag>
# tag an image (creates an additional reference, not a copy)
docker tag jboss/wildfly myimage:v1
docker tag <image-name>:<tag> <username>/<new-image-name>:<new-tag>
# remove
docker rmi <image-name>:<tag>
docker rmi -f 27d783d4d74d # by ID, forced
docker rmi -f $(docker images -q) # every image on the host
docker search returns the repository name, description, star count, whether the image is
Official (maintained by the upstream project) and whether it is an Automated build. Prefer
official images for base layers.
Container Commands
Running
# interactive shell inside a container
docker run -it ubuntu /bin/bash
docker run -it ubuntu:16.04 /bin/bash # default user is root
# detached, named, with a published port
docker run --name mywildfly -d -p 8080:8080 jboss/wildfly
# remove the container automatically when it exits
docker run --rm busybox:latest /bin/echo "Hello world"
# attach to a user-defined network
docker network create mynetwork
docker run --name mywildfly-net -d --net mynetwork -p 8080:8080 jboss/wildfly
# mount a host directory into the container
docker run --name mywildfly-volume -d \
-v myfolder/:/opt/jboss/wildfly/standalone/deployments/ \
-p 8080:8080 jboss/wildfly
# create without starting
docker create --name hello-world-cont helloworld
The -p host:container flag publishes a port. In -p 8080:8080 the first number is the host
port and the second is the port inside the container; they need not match.
Listing and lifecycle
docker ps # running containers only
docker ps -a # all containers, including stopped
docker ps -a -q # all container IDs only
docker start <name|id>
docker stop <name|id> # SIGTERM, then SIGKILL after a grace period
docker stop -t 1 <name|id> # one-second timeout
docker restart <name|id>
docker pause <name|id>
docker unpause <name|id>
docker kill <name|id> # SIGKILL immediately
docker rename <old-name> <new-name>
A container is always in one of these states: created, restarting, running, removing,
paused, exited, or dead. Filter on them:
docker ps --filter status=running
docker ps --filter status=paused
docker ps -a --filter 'exited=0'
Removing
docker rm <name|id> # a stopped container
docker rm -f <name|id> # force-stop, then remove
docker rm -f $(docker ps -aq) # every container
docker rm $(docker ps -q -f "status=exited") # stopped containers only
docker container prune # all stopped containers
Inspecting and interacting
docker logs <name|id>
docker logs -f <name|id> # follow
docker logs --tail 100 <name|id> # last 100 lines
docker exec -it <name|id> /bin/bash # new interactive process in a running container
docker exec <name|id> ls
docker exec <name|id> hostname
docker attach <name|id> # attach to the main process's stdio
docker top <name|id> # processes running inside
docker diff <name|id> # filesystem changes since the image
docker inspect <name|id> # full low-level JSON
docker inspect --format '{{ .State.Status }}' <id>
docker inspect --format '{{ .State.Pid }}' <id>
docker inspect --format '{{ .NetworkSettings.IPAddress }}' <id>
docker cp <name|id>:/path/in/container ./local/path
docker cp ./local/file <name|id>:/path/in/container
docker exec fails if the container is paused — unpause it first. docker diff marks each change
as A (added), D (deleted), or C (changed).
Resource limits and monitoring
docker stats # live resource usage, all containers
docker stats <name|id> # one container; Ctrl+C to exit
docker system df # disk used by images, containers, volumes
docker events # real-time event stream from the daemon
docker info
# cap memory and CPU
docker run -m 512m --cpu-quota 50000 <image>
--cpu-quota 50000 against the default 100000-microsecond period allows roughly half a CPU core.
Setting limits matters: by default a container may consume all available host memory.
Networking
A Docker network lets containers communicate. Containers on the same user-defined network can reach each other by container name, which is the cleanest way to wire multi-container applications.
docker network ls # list networks
docker network create mynetwork
docker network inspect bridge
docker network connect mynetwork <container>
docker network disconnect mynetwork <container>
docker network rm mynetwork
docker network prune # remove all unused networks
docker network --help
Options available when connecting a container to a network include --alias (a network-scoped
alias), --ip and --ip6 (static addresses), and --link-local-ip.
Volumes and Persistent Data
By default, every file created inside a container lives in that container's writable layer. That data does not persist once the container is removed, and it is awkward to extract if another process needs it. Volumes solve both problems.
docker volume create mydata
docker volume ls
docker volume inspect mydata
docker volume rm mydata
docker volume prune
docker volume --help
# named volume mounted into a container
docker run -d -v mydata:/var/lib/mysql mysql
# bind-mount a host directory
docker run -d -v /host/path:/container/path nginx
# read-only mount
docker run -d -v mydata:/container/path:ro nginx
# reuse another container's volumes
docker run -it --volumes-from ubuntucontainer16 --name ubuntucontainer1604 ubuntu:16.04
The same volume can be mounted into many containers simultaneously — which is how data is shared between them, though concurrent writers need application-level coordination.
Dockerfile Reference
| Instruction | Purpose |
|---|---|
FROM |
Sets the base image for subsequent instructions. Must be first. |
RUN |
Executes a command in a new layer on top of the current image and commits the result. Build-time. |
CMD |
Default command executed when a container starts. Only the last CMD takes effect. |
ENTRYPOINT |
Configures the container to run as an executable. |
COPY |
Copies files or directories from the build context into the image. |
ADD |
As COPY, but additionally expands local tar archives and accepts remote URLs. |
ENV |
Sets an environment variable, available at build time and run time. |
ARG |
Defines a build-time variable, passed via --build-arg. Not available at run time. |
EXPOSE |
Documents the port the container listens on. |
VOLUME |
Creates a mount point marked as holding externally mounted data. |
WORKDIR |
Sets the working directory for following RUN, CMD, ENTRYPOINT, COPY, and ADD. |
USER |
Sets the username or UID used to run the image. |
LABEL |
Adds metadata to the image. |
ONBUILD |
Registers an instruction to run later, when this image is used as a base. |
HEALTHCHECK |
Defines how the daemon tests that the container is still working. |
MAINTAINERappears in older material but is deprecated. Use a label instead:LABEL maintainer="you@example.com".
EXPOSE does not publish a port
This trips people up. EXPOSE is documentation — it records the port the application listens on.
It does not make the port reachable from the host. Publishing requires -p at run time, or
-P to map all exposed ports to random host ports.
COPY vs ADD
Both copy files from the build context into the image.
COPYcopies files and directories, and nothing more.ADDalso auto-extracts local tar archives and can fetch remote URLs.
Prefer COPY. Its behaviour is predictable, whereas ADD can surprise you by unpacking an
archive you intended to copy intact. Use ADD deliberately when you want tar extraction; for
remote files prefer an explicit RUN curl, so the download and its cleanup occupy one layer.
RUN vs CMD vs ENTRYPOINT
These three are routinely confused, and the distinction is about when and how they execute.
RUN is a build step. Its result is committed into the image as a layer. A Dockerfile may
have many RUN instructions, each layering on the last.
CMD is the default command run when a container launches from the image. A Dockerfile has
only one effective CMD, and it is overridden by any command supplied on the docker run line:
docker run myimage # runs CMD
docker run myimage /bin/bash # overrides CMD entirely
ENTRYPOINT also defines what runs at startup, but is not casually overridden — arguments
given to docker run are appended to it as parameters rather than replacing it. It has two forms:
ENTRYPOINT ["executable", "param1", "param2"] # exec form, preferred
ENTRYPOINT command param1 param2 # shell form
The exec form is preferred because it runs the executable as PID 1 directly, so it receives
signals such as SIGTERM and shuts down cleanly. The shell form wraps the command in
/bin/sh -c, which swallows signals and leads to containers that take ten seconds to stop.
The idiomatic combination is ENTRYPOINT for the fixed executable and CMD for the default
arguments a user might wish to replace.
Building Images
docker build -t ImageName:TagName <context-directory>
| Element | Meaning |
|---|---|
-t |
Tags the image with a name and optional tag |
ImageName |
The name given to the image |
TagName |
The version label; defaults to latest if omitted |
| context | Directory sent to the daemon; . means the current directory |
docker build -t mongodbimage:1.0 .
Because the Dockerfile sits in the working directory, . is used to denote it. Use -f when the
Dockerfile lives elsewhere or has a non-default name.
Creating an image manually (and why you shouldn't)
It is instructive to build an image by hand once, because it shows what docker build automates.
Start a base container, copy an artifact in, and commit the result:
docker run -dit openjdk:8-jdk-alpine
docker ps # note the generated container name
docker container exec <container> ls /tmp
docker container cp build/libs/hello-world-rest-api.jar <container>:/tmp
docker container exec <container> ls /tmp
# commit the container's current state as a new image
docker container commit <container> pravat/hello-world-rest-api:manual1
# commit, and set the default command at the same time
docker container commit \
--change='CMD ["java","-jar","/tmp/hello-world-rest-api.jar"]' \
<container> pravat/hello-world-rest-api:manual2
docker run -p 8080:8080 pravat/hello-world-rest-api:manual2
This works, but it is not reproducible — nothing records how the image was made. Use a Dockerfile
for anything that matters. docker commit is best reserved for capturing the state of a container
mid-debug.
Worked Examples
Apache httpd serving a static page
FROM httpd:2.4
COPY ./index.html /usr/local/apache2/htdocs/
EXPOSE 80
docker build -t httpdimage:1.0 .
docker run -d -p 8081:80 httpdimage:1.0
Open http://localhost:8081 to see the page. If localhost does not resolve, substitute the host's
IP address.
Tomcat with a WAR file
FROM tomcat:8.0.20-jre8
COPY ./SampleAntProject.war /usr/local/tomcat/webapps/SampleAntProject.war
The WAR and the Dockerfile must both be in the build context:
docker build -t tomcatimage:8.0 .
docker run -d -p 8088:8080 tomcatimage:8.0
Then browse to http://localhost:8088/SampleAntProject.
Spring Boot application
FROM openjdk:8-jdk-alpine
ADD build/libs/hello-world-rest-api.jar hello-world-rest-api.jar
ENTRYPOINT ["sh","-c","java -jar /hello-world-rest-api.jar"]
docker build -t pravat/hello-world-rest-api:dockerfile1 .
docker run -p 8080:8080 pravat/hello-world-rest-api:dockerfile1
A more current version of the same image, using COPY, the exec form, and a non-root user:
FROM eclipse-temurin:21-jre-alpine
WORKDIR /app
COPY build/libs/hello-world-rest-api.jar app.jar
RUN addgroup -S spring && adduser -S spring -G spring
USER spring
EXPOSE 8080
ENTRYPOINT ["java","-jar","/app/app.jar"]
Java web application on Tomcat
FROM tomcat:8.0.20-jre8
COPY target/java-web-app*.war /usr/local/tomcat/webapps/java-web-app.war
docker build -t dockerhandson/java-web-app:1.0 .
docker run -d --name javaapp -p 8080:8080 dockerhandson/java-web-app:1.0
WildFly with an admin user
FROM jboss/wildfly
RUN /opt/jboss/wildfly/bin/add-user.sh admin <password> --silent
EXPOSE 8080 9990
CMD ["/opt/jboss/wildfly/bin/standalone.sh", "-b", "0.0.0.0", "-bmanagement", "0.0.0.0"]
docker build -t mywildfly .
docker run -it -p 8080:8080 -p 9990:9990 mywildfly
Never bake a credential into a Dockerfile for anything beyond a local experiment. Anyone who can pull the image can read it with
docker history. Pass secrets at run time, or use BuildKit secret mounts.
Publishing to a Registry
# authenticate (default registry is https://index.docker.io/v1/)
docker login
docker login <registry-host>
# tag the local image with your namespace
docker tag <local-image>:<tag> <username>/<repository>:<tag>
# push
docker push <username>/<repository>:<tag>
docker logout
Find the image ID to tag with docker images. If a push is rejected on authentication, run
docker login and retry. Docker Hub's free tier allows one private repository and unlimited
public ones.
Moving images without a registry
docker save -o backup_container.tar <image>:<tag> # export image to a tar file
docker load -i backup_container.tar # import it elsewhere
docker export <container> > container.tar # export a container filesystem
docker import container.tar <image-name>:<tag>
save and load work on images and preserve layers and tags. export and import flatten a
container's filesystem and discard history — use save/load unless you specifically want the
flattening.
Docker Compose
Compose defines and runs multi-container applications from a single YAML file, replacing long
chains of docker run commands.
services:
mongodb:
image: mongo:6
container_name: app-mongodb
ports:
- "27017:27017"
volumes:
- mongodb_data:/data/db
networks:
- app-network
backend:
build: ./app-api
container_name: app-api
ports:
- "5002:5002"
environment:
- MONGO_URI=mongodb://mongodb:27017/app_db
depends_on:
- mongodb
networks:
- app-network
frontend:
build: ./app-ui
container_name: app-ui
ports:
- "3000:3000"
depends_on:
- backend
networks:
- app-network
volumes:
mongodb_data:
networks:
app-network:
driver: bridge
docker compose up -d # create and start everything, detached
docker compose ps
docker compose logs -f backend
docker compose exec backend sh
docker compose build # rebuild images
docker compose stop
docker compose down # stop and remove containers and networks
docker compose down -v # also remove named volumes
Note the service names. Because Compose puts all three services on one network, backend reaches
the database at mongodb://mongodb:27017 — the service name resolves as a hostname. That is why
no IP addresses appear anywhere in the file.
Modern Docker ships Compose v2 as the
docker composesubcommand. The standalonedocker-composebinary and the leadingversion: '3.8'key are both legacy; theversionkey is now ignored and can be deleted.
Docker Swarm
Swarm is Docker's built-in clustering and orchestration mode, turning a group of Docker hosts into a single virtual host.
docker swarm init # initialise a manager node
docker swarm join --token <token> <manager-ip>:2377 # join from a worker
docker node ls
docker service create --name web --replicas 3 -p 80:80 nginx
docker service ls
docker service ps web
docker service scale web=5
docker service update --image nginx:1.27 web
docker stack deploy -c docker-compose.yml mystack
docker service rm web
For release strategy, a blue/green deployment is the common approach: run the new version alongside the old, shift traffic once it is healthy, and keep the old version available for rollback.
In practice most organisations have standardised on Kubernetes for orchestration. Swarm remains useful for small clusters and is far simpler to learn, but new production platforms are rarely built on it.
Build and Deployment: Before and After Docker
Before Docker
Build. A developer pushes a change to source control. CI detects the new code, rebuilds the project, runs the tests, and produces an application package such as a JAR, WAR, or EAR. CI stores that package as a build artifact in a repository.
Deployment. Dependencies and configuration are set up on the target application servers, physical or virtual. The package is downloaded. The application is started.
The problems. Packaging and deploying across multiple environments is genuinely difficult. Every environment must be prepared before deployment. And applications that work in one environment may fail in another because of differing operating systems, dependencies, libraries, or software versions.
After Docker
Build. A developer pushes a change. CI rebuilds, tests, and produces the application package — then also builds a Docker image containing the application code, its dependencies, and its configuration. CI pushes that image to a registry, whether public (Docker Hub) or private (Nexus, JFrog, ECR).
Deployment. Pull the image. Start it, which creates the container in which the application runs.
The gain. The identical artifact runs in development, test, and production. Environment preparation collapses into the image build, which happens once.
Monolithic vs Microservices
Containers are not required to build microservices, but they suit the style particularly well, and Docker's rise is closely tied to it.
Monolithic architecture — a single code base with multiple modules, divided by business or technical feature, with one build system producing one deployable binary.
| Monolithic pros | Monolithic cons |
|---|---|
| Simple to develop | Difficult to understand and modify at scale |
| Simple to deploy a single package | Tightly coupled |
| Easier to debug and trace errors | Entire application redeployed on each update |
| Simple to test | One bug can bring down everything |
| Scaling requires scaling the whole application, not the busy part | |
| A change in one module can affect another through the shared code base |
Microservices architecture — an application arranged as a collection of loosely coupled services, each responsible for a discrete task, developed, deployed, and maintained independently, communicating through simple APIs.
| Microservices pros | Microservices cons |
|---|---|
| Loosely coupled | Inter-service communication is complex; requests travel over APIs |
| Small code bases, easier to understand and modify | Integration testing is harder — dependent services must be deployed first |
| Each service deploys independently | Debugging spans many services, each with its own logs |
| Each service scales independently | Deployment needs coordination across services |
| Each service can use a different technology stack | Operational surface is much larger |
Hands-On Labs
Both labs run on a cloud VM so that the published port is reachable over the internet.
Provisioning the instance
- Open the EC2 console and select your region.
- Launch an instance; give it a name.
- Choose Ubuntu Server 20.04 LTS (or a current LTS) as the AMI.
- Choose a
t2.smallinstance type. - Create a new key pair and download it. Keep the
.pemfile private — it is the only copy. - Under network settings, keep port 22 for SSH and add an inbound rule for the application port (HTTP/80 for the first lab, custom TCP/3000 for the second).
- Launch, then connect using EC2 Instance Connect or SSH.
Install Docker using the Ubuntu steps given earlier, then refresh the shell so group membership applies.
Lab 1 — Build and run a hello-world image
sudo chown ubuntu:ubuntu -R /opt
cd /opt
docker images
docker run --rm busybox:latest /bin/echo "Hello world"
# fetch a prepared Dockerfile, build it, and run it
wget <dockerfile-url> -O Dockerfile
docker build -t helloworld .
docker run -d -p 80:8080 helloworld
docker ps -a
docker rm -f <container-id>
docker rmi <image-id>
Note the mapping -p 80:8080: the application listens on 8080 inside the container, published on
port 80 of the host, which is the port opened in the security group.
Lab 2 — Containerise a React application
docker version
sudo chown ubuntu:ubuntu -R /opt
cd /opt
git clone https://github.com/cwackerfuss/react-wordle.git
cd react-wordle
# -f names a Dockerfile that is not at the context root
docker build -t reactle:dev -f docker/Dockerfile .
docker run -d -p 3000:3000 --name reactle-dev reactle:dev
Browse to the instance's public IP on port 3000. This lab is worth doing because it uses -f to
build from a Dockerfile held in a subdirectory while keeping the repository root as the build
context — a very common real-world arrangement.
Troubleshooting
Error response from daemon: No build stage in current context
The Dockerfile is malformed — commonly a missing or misspelled FROM as the first instruction.
The daemon validates syntax before executing, so fix the file and rebuild.
Cannot connect to the Docker daemon
The daemon is not running, or your user lacks permission. Check with docker info and
systemctl status docker; confirm your user is in the docker group.
Image pull fails with "not found"
Check spelling and the tag. If no tag is given, Docker assumes :latest, which may not exist for
that repository. docker search confirms whether the repository is real.
Port is already allocated
Another process or container holds the host port. Find it with docker ps and either stop it or
publish on a different host port.
docker exec returns an error
The container is paused or not running. docker unpause or docker start it first.
Container exits immediately
Its main process finished. A container lives only as long as PID 1. Check docker logs, and
confirm that CMD or ENTRYPOINT starts a long-running foreground process rather than a command
that returns.
Disk filling up
Images, stopped containers, build cache, and orphaned volumes all accumulate. Inspect with
docker system df, then reclaim:
docker container prune
docker image prune -a
docker volume prune
docker system prune -a --volumes # aggressive; removes everything unused
Quick Reference
# information
docker --version / docker version / docker info
docker system df
# images
docker images docker pull <img>[:tag]
docker build -t <name>:<tag> . docker tag <src> <dst>
docker push <user>/<repo>:<tag> docker rmi <img>
docker history <img> docker save -o f.tar <img> / docker load -i f.tar
# containers
docker run -d -p <h>:<c> --name <n> <img>
docker run -it <img> /bin/bash docker run --rm <img> <cmd>
docker ps / docker ps -a docker logs -f <n>
docker exec -it <n> /bin/bash docker inspect <n>
docker stop <n> / docker start <n> docker rm -f <n>
docker stats docker top <n>
# bulk cleanup
docker stop $(docker ps -a -q)
docker rm -f $(docker ps -a -q)
docker rmi -f $(docker images -q)
docker system prune -a
# networks and volumes
docker network ls / create / inspect / rm / prune
docker volume ls / create / inspect / rm / prune
# compose
docker compose up -d / ps / logs -f / down [-v]
# swarm
docker swarm init docker service create --replicas N
docker service ls / scale / update docker stack deploy -c file stack
Best Practices
Use official base images, and pin them to a specific tag rather than latest. A build that
depends on latest is a build that is not reproducible.
Prefer small base images. An Alpine or slim variant often cuts image size by an order of magnitude, which speeds every pull in every environment.
Use multi-stage builds so that compilers and build tooling do not ship to production:
FROM node:20-alpine AS build
WORKDIR /app
COPY package*.json ./
RUN npm ci
COPY . .
RUN npm run build
FROM nginx:1.27-alpine
COPY --from=build /app/build /usr/share/nginx/html
Order instructions from least to most frequently changed. Copy dependency manifests and install dependencies before copying source code, so that editing a source file does not invalidate the dependency layer.
Always add a .dockerignore. Without it the whole working directory is sent to the daemon,
including node_modules, .git, and any .env — which may then be baked into a published image.
Run as a non-root user. Add a USER instruction. Containers default to root, and root in the
container is root on the host kernel.
Keep one concern per container. A container should run a single process that stays in the foreground. Use Compose or an orchestrator to assemble several.
Never bake secrets into images. Pass them as environment variables at run time, or mount them.
Anything in a layer is visible via docker history.
Set resource limits in production. An unconstrained container can exhaust host memory.
Use volumes for anything that must survive the container. Treat containers themselves as disposable.
Combine related RUN commands to reduce layer count, and clean up in the same layer that
created the mess:
RUN apt-get update \
&& apt-get install -y --no-install-recommends curl \
&& rm -rf /var/lib/apt/lists/*
Add a HEALTHCHECK so the runtime can tell the difference between a container that is running
and an application that is working.