Docker Handbook
Docker packages an application and its runtime dependencies into an image, then runs that image as an isolated container. This handbook explains how to build images, run containers, and manage an application with Docker Compose. Examples use Linux containers and the modern docker compose command.
A Dockerfile describes how to build one image. A compose.yaml describes how services run together: their images, ports, configuration, networks, and storage.
Setup & concepts
Install Docker Desktop on Windows or macOS, or Docker Engine with the Compose plugin on Linux. Start the engine; on Windows select Linux containers for these examples. Run the following checks in a terminal.
docker version
docker info
docker compose version
docker run --rm hello-worlddocker versiondisplays client and server versions. A client version alone does not prove that the engine is reachable.docker inforeports engine configuration, storage, and running container counts.docker compose versionconfirms that the Compose plugin is available.docker run --rm hello-worldpulls the test image if necessary, creates a container, prints a message, and removes the container after it exits.
| Concept | Meaning |
|---|---|
| Image | A reusable template with filesystem layers and runtime defaults. Tags are movable names; digests identify exact image content. |
| Container | An instance of an image with its own writable layer and processes. Stopping keeps that layer; removing deletes it. |
| Registry | A service that stores and distributes images, such as Docker Hub or a private registry. |
| Volume | Docker-managed storage that can outlive a container. Persistence does not replace backups. |
| Bind mount | A host path made visible inside a container, useful for development files. |
| Network | A communication boundary. User-defined bridge networks provide container-name DNS. |
Linux containers share a kernel rather than booting a full guest operating system each. Docker Desktop supplies a Linux environment on Windows and macOS. Images must also match the target OS and CPU architecture.
Example application: a persistent visit counter
Create a new directory containing package.json, package-lock.json, server.mjs, Dockerfile, .dockerignore, and compose.yaml. The web service increments a Redis counter on each request. Its /health endpoint checks Redis without incrementing the counter.
package.json
{
"name": "docker-handbook-demo",
"version": "1.0.0",
"private": true,
"type": "module",
"dependencies": {
"redis": "4.7.0"
}
}With Node.js and npm installed locally, run this once in the example directory to generate the lockfile. Keep the lockfile with the source so npm ci can install the recorded dependency graph.
npm install --package-lock-onlyserver.mjs
import http from 'node:http'
import { createClient } from 'redis'
const client = createClient({ url: process.env.REDIS_URL || 'redis://localhost:6379' })
client.on('error', error => console.error('Redis:', error.message))
await client.connect()
const server = http.createServer(async (request, response) => {
try {
if (request.url === '/health') {
await client.ping()
response.end('ok')
return
}
const visits = await client.incr('visits')
response.setHeader('Content-Type', 'text/plain')
response.end('Visits: ' + visits + '\n')
} catch {
response.writeHead(503)
response.end('Redis unavailable')
}
})
server.listen(3000, '0.0.0.0')
process.on('SIGTERM', () => {
server.close(async () => {
await client.quit()
process.exit(0)
})
})The app listens on 0.0.0.0:3000 so connections can reach it through the container's network interface. Listening only on 127.0.0.1 inside the container would prevent published-port traffic from reaching it. The Redis client logs connection errors and reconnects; request failures return HTTP 503. The SIGTERM handler closes the HTTP server before closing Redis. Real deployments should also bound shutdown time and configure connection retry limits appropriate to their availability requirements.
Dockerfile explained
# syntax=docker/dockerfile:1
FROM node:24-alpine
WORKDIR /app
ENV NODE_ENV=production
COPY package.json package-lock.json ./
RUN npm ci --omit=dev
COPY --chown=node:node server.mjs ./
USER node
EXPOSE 3000
CMD ["node", "server.mjs"]# syntax=docker/dockerfile:1selects the stable Dockerfile frontend used by BuildKit.FROM node:24-alpinesupplies Node.js, npm, and a minimal Alpine Linux userspace. Alpine uses musl libc; native dependencies may require a Debian-based image instead. Tags can change; use a verified digest for reproducible release builds.WORKDIR /appcreates and selects the working directory for later instructions and the default process.ENV NODE_ENV=productionsupplies a default environment variable during subsequent build steps and at runtime. It does not itself remove development dependencies.COPY package.json package-lock.json ./copies dependency metadata first, keeping dependency installation cacheable when only application source changes.RUN npm ci --omit=devexecutes during the build, installs from the lockfile, and excludes development dependencies from disk. A missing or incompatible lockfile fails the build.COPY --chown=node:node server.mjs ./adds the application with ownership assigned to the base image's built-in node user.USER noderuns subsequent instructions and the default container process as that non-root user. Files copied earlier remain readable; writable application data needs deliberately assigned permissions.EXPOSE 3000documents the listening port. Publishing requires-por Composeports.CMD ["node", "server.mjs"]defines the runtime default. Exec form starts Node directly, allowing it to receive stop signals. Arguments after the image indocker runreplace CMD.
RUN executes while creating an image; CMD runs when a container starts. ENTRYPOINT defines an executable that is normally retained when runtime arguments are supplied; CMD can provide its default arguments. ARG accepts build-time inputs and is not automatically a runtime environment variable. Neither ARG nor ENV is appropriate for embedding secrets. Prefer COPY for ordinary local files; ADD has additional download and archive behavior that should be intentional.
Build context, .dockerignore & caching
flowchart LR
D["Dockerfile instructions"] --> B["docker build"]
C["Build context filtered by .dockerignore"] --> B
B --> I["Image"]
I -->|docker run: create and start| R["Container with its own writable layer"]
Build creates an image; run creates a container from it. Multiple containers can use the same image while keeping separate writable layers.
Save the following as .dockerignore beside the Dockerfile. It excludes host dependencies, repository metadata, local credentials, logs, and build output from the build context. The exception allows an example environment file to remain available.
node_modules
.git
.env
.env.*
!.env.example
npm-debug.log*
distdocker build -t handbook-demo:1.0 .
docker build --pull -t handbook-demo:1.0 .
docker build --no-cache -t handbook-demo:1.0 .-t handbook-demo:1.0 names and tags the result. The final . selects the current directory as build context; COPY sources are resolved against that context, not the Dockerfile's directory. With -f path/Dockerfile, the final context argument still controls available files.
The first command reuses valid cached build steps. --pull checks for a newer base image; --no-cache disables build-step cache reuse but does not itself request a newer base. When copied inputs change, dependent later steps need rebuilding. Install dependencies before copying frequently changing source to avoid unnecessary reinstalls.
Multi-stage Dockerfile: keep build tools out of runtime
This independent example uses a separate directory. Save this standard-library-only application as main.go:
package main
import (
"fmt"
"net/http"
)
func main() {
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
fmt.Fprintln(w, "Hello from a multi-stage image")
})
http.ListenAndServe(":8080", nil)
}Save the following Dockerfile there, then build with docker build -t handbook-go:1.0 . and run with docker run --rm -p 127.0.0.1:8082:8080 handbook-go:1.0. Open http://localhost:8082; Ctrl+C stops the foreground container and --rm removes it.
# syntax=docker/dockerfile:1
FROM golang:1.26-alpine AS build
WORKDIR /src
COPY main.go ./
RUN CGO_ENABLED=0 go build -trimpath -ldflags="-s -w" -o /out/server main.go
FROM scratch
COPY --from=build /out/server /server
USER 65532:65532
EXPOSE 8080
ENTRYPOINT ["/server"]AS build names the compiler stage. CGO_ENABLED=0 disables C interop for this application, producing a binary that can run without a shared C runtime. -trimpath removes build filesystem paths; -ldflags="-s -w" omits symbol and debugging information. The second FROM starts an empty runtime filesystem. COPY transfers only the resulting binary, and the numeric USER works without a user database.
The final image contains no compiler, package manager, or shell. Consequently, docker exec ... sh cannot work there. This minimal HTTP server does not need certificates or timezone files; applications making HTTPS requests or using named timezones must supply those assets or use a suitable runtime base. For module dependencies, copy go.mod and go.sum and download modules before copying source.
compose.yaml explained
flowchart TD
H["Host browser: localhost:8080"] -->|published 127.0.0.1:8080 to port 3000| W
subgraph N["Compose default network"]
W["web: Node on port 3000"] -->|Redis requests to redis:6379| R["redis: port 6379"]
end
R -->|append-only data at /data| V["Named volume: redis-data"]
These arrows show request and storage flow. Web reaches Redis by service name on the project network; Redis needs no published host port. The named volume survives ordinary container replacement and compose down.
Return to the Node.js example directory and save this as compose.yaml. YAML indentation uses spaces. Modern Compose does not need a top-level version field.
name: docker-handbook
services:
web:
build:
context: .
dockerfile: Dockerfile
image: handbook-demo:1.0
ports:
- "127.0.0.1:8080:3000"
environment:
REDIS_URL: redis://redis:6379
depends_on:
redis:
condition: service_healthy
healthcheck:
test: ["CMD", "node", "-e", "fetch('http://127.0.0.1:3000/health').then(r => process.exit(r.ok ? 0 : 1)).catch(() => process.exit(1))"]
interval: 10s
timeout: 3s
retries: 3
start_period: 10s
restart: unless-stopped
redis:
image: redis:7-alpine
command: ["redis-server", "--appendonly", "yes"]
volumes:
- redis-data:/data
healthcheck:
test: ["CMD", "redis-cli", "ping"]
interval: 5s
timeout: 3s
retries: 5
restart: unless-stopped
volumes:
redis-data:namesets the project name used for resource grouping.docker compose -p other-name ...overrides it, creating a separate project and different project-scoped storage.servicesdeclares web and redis.build.contextselects the web build inputs anddockerfileselects the recipe.imagesupplies its resulting tag;up --buildexplicitly builds it.portsmaps host address and port to the container port. Here the app is available only through host loopback athttp://localhost:8080. Omitting the host address normally publishes on all host interfaces.environmentinjects runtime values. The hostnameredisis the Compose service name on the automatically created default network. Inside web, localhost means web itself, not Redis or the host.depends_onwithcondition: service_healthydelays web startup until Redis passes its health check. Simple dependency ordering alone does not establish readiness. This startup gate does not continually restart web if Redis later becomes unavailable.healthcheck.testruns inside each container. Exec-form CMD needs no shell; each executable must exist in its image. The web check uses Node's built-in fetch, and Redis uses redis-cli.intervalschedules checks,timeoutlimits a check, andretriescounts consecutive failures before marking unhealthy. Web'sstart_periodgives startup failures a grace period. Unhealthy status alone does not restart a container.restart: unless-stoppedasks the engine to restart exited containers unless intentionally stopped. Applications still need to handle dependency outages.- Redis's
commandreplaces its image's default CMD to enable append-only persistence. Redis's existing entrypoint remains in use. redis-data:/datamounts a named volume at Redis's data directory. The top-level volumes entry declares it. Compose normally prefixes its actual name with the project name.
Redis has no published host port; web reaches it over the project network. This is a local learning stack without Redis authentication or TLS. Do not expose it as a public database. Its persistent counter survives container replacement while the volume is retained, subject to Redis persistence and crash-durability behavior.
Compose can interpolate ${VARIABLE} values from the shell or a project .env file. Interpolation does not automatically inject every variable into a container: use environment or env_file for that. $$ escapes a literal dollar sign for container-side expansion. Use docker compose config to inspect the resolved model, remembering that its output can reveal configuration secrets.
Compose commands: build, inspect & stop
docker compose config --quiet
docker compose up --build -d --wait
docker compose ps
docker compose logs --tail 100 -f web
docker compose exec web sh
docker compose exec redis redis-cli GET visits
docker compose run --rm --no-deps web node --version
docker compose stop
docker compose start
docker compose restart web
docker compose downconfig --quietvalidates the Compose model without printing it or starting services.up --build -d --waitbuilds web, creates the project resources, starts services in the background, and waits for running or healthy state. Open localhost:8080 twice to observe the counter increasing. A modern Compose plugin is required for --wait.psreports service state, published ports, and available health status.logs --tail 100 -f webprints recent web logs and follows new output. Ctrl+C stops following logs without stopping the detached service.exec web shopens a shell in the running web service; type exit to leave.exec redis redis-cli GET visitsreads the counter directly. Useexec -Tto disable the default pseudo-terminal in automation.run --rm --no-deps web node --versioncreates a temporary one-off web container, overrides CMD, skips dependencies, and removes it afterward. Compose run does not publish the service ports by default.stopstops existing containers;startstarts those same containers. Neither applies edited image or service definitions.restart webrestarts the existing web container. After source or configuration changes, useup --build -d --waitto rebuild and recreate as needed.downstops and removes project containers and ordinary project networks. The declared named volume remains for the next up.
Run these commands from the example directory, or specify docker compose -f path/to/compose.yaml .... Service names such as web are different from generated container names. Compose commands target the selected project, so keep the same project name when returning to persistent data.
Everyday workflows: what to run and why
Use these recipes from the directory containing your compose.yaml. They are separate scenarios, not one script to execute from top to bottom. Here web and redis are service names from the example stack; substitute your own service names. docker compose config --services lists the available names.
Start your workday
You have opened a project and need its application and dependencies running while you work. Start the stack in the background so the terminal stays available, then check which services are running.
docker compose up -d
docker compose ps
# First run, or after changing source copied into the image:
docker compose up --build -dup -d creates missing containers and starts the stack, reusing existing images where possible. It can also recreate services whose configuration or image changed. --build explicitly builds services with a build definition before starting them; use it on the first run or after changing a Dockerfile, dependencies, or source copied into an image. Cached steps can still be reused. -d means detached: closing the terminal does not stop the services. Add --wait when you need Compose to wait for running or healthy state before returning.
Apply code or configuration changes
You edited the app but the browser still shows old behavior. Choose a command based on how the changed files reach the container.
# Rebuild and recreate web after an application change:
docker compose up --build -d web
# Apply a changed environment or port mapping from compose.yaml:
docker compose up -d web
# Restart the existing process without applying new configuration:
docker compose restart web- Source copied by the Dockerfile: rebuild with
up --build -d web. This handbook's Node application uses COPY, so source changes require a new image and container. - Source bind-mounted for development: changes are already visible inside the container. A development server with file watching can reload them; otherwise restart the process. A bind mount alone does not provide automatic reload.
- Compose environment, ports, or mounts: use
up -d webto apply the changed service definition. Restart reuses the old container configuration. - A stuck process with unchanged files and configuration:
restart webgives the process a fresh start. Inspect logs first so a restart does not hide the evidence you need.
Targeting web limits the requested work, but Compose may also start its dependencies. Use --no-deps only when those dependencies are already running and you deliberately want to leave them alone. There is normally no need to run down before up; up reconciles the existing stack and avoids unnecessary interruption to other services.
Investigate a failure
The page returns an error, a service keeps exiting, or startup appears stuck. Check state first, then recent logs, then a small command inside the affected service.
docker compose ps -a
docker compose logs --tail 100 web redis
docker compose logs --since 10m -f web
docker compose exec web node --version
docker compose exec redis redis-cli PINGps -a includes exited service containers. Reading logs for both web and redis helps distinguish an app failure from a dependency failure. --since 10m limits logs to the last ten minutes and -f follows new messages while you reproduce the problem. Ctrl+C ends the log view without stopping the detached stack. node --version checks the runtime actually installed in web; Redis's PING should return PONG. Exec requires a running container, so use logs first for one that exits immediately.
Open a shell inside a running container
You need to inspect paths, installed tools, or file permissions in the container's actual environment rather than on your host machine.
# Alpine-based web in this handbook has sh:
docker compose exec web sh
# For a service whose image includes Bash:
docker compose exec web bash
# General form: replace xxx with a Compose service name:
docker compose exec xxx bash
# Inside the shell:
pwd
ls
exitChoose one shell command that matches your image. docker compose exec xxx bash means “run Bash inside the running service named xxx”; xxx is a placeholder, not a container ID. This handbook's Alpine-based web image includes sh but does not include Bash, so use docker compose exec web sh for it. An error such as “executable file not found” often means that the requested shell is absent. Minimal images may contain no shell at all.
Compose exec allocates an interactive terminal by default; unlike docker exec -it CONTAINER sh, it usually needs no -it. Commands entered after connecting run inside the container until you type exit. Exiting this extra shell leaves the service running. Use the shell to diagnose problems; save lasting application fixes in source and rebuild, because container-local edits disappear when the container is replaced. Edits to a writable bind mount also change the host files.
Run a command without opening a shell
You want a runtime check, a database query, or a project maintenance command. Execute it directly so there is no interactive shell to manage.
# Execute in the already running web service:
docker compose exec web node --version
# Run in a new temporary container without starting dependencies:
docker compose run --rm --no-deps web node --version
# Disable terminal allocation for scripts or redirected output:
docker compose exec -T redis redis-cli GET visitsexec uses an existing running container and its current environment. run --rm creates a new one-off container from the service definition and removes that container when the command ends; it can run even when the regular service is stopped. --no-deps prevents starting dependencies and is suitable for this version check, which needs no Redis connection. Leave it out for a task that needs dependencies. The temporary container still uses configured mounts, so --rm does not undo writes to shared data.
In another project, replace node --version with an actual supported command such as npm test or npm run migrate. The demonstration application defines neither script, and its production image omits development dependencies, so those examples require a suitable project and development image. For CI or output redirection, exec -T disables pseudo-terminal allocation. Use your migration tool's normal safeguards before running a command that changes database data.
Refresh a service that uses a registry image
You intentionally want the latest image currently published under the Redis tag in compose.yaml. Download it, then reconcile the running service with that image.
docker compose pull redis
docker compose up -d redis
docker compose ps
docker compose logs --tail 50 redispull redis downloads the image but does not replace the running Redis container. up -d redis recreates it if its image changed, keeping the named data volume. Check state and logs afterward. This can interrupt dependent requests while Redis restarts. Back up important data and read release compatibility guidance before database upgrades; avoid treating an upgrade as a routine fix for an unexplained error. Services built from local source instead use the build workflow above.
Pause for lunch or finish the day
# Pause; keep the existing containers:
docker compose stop
# Resume those containers later:
docker compose start
# Finish; remove containers and the project network:
docker compose down
# Recreate the stack next time, keeping its named volume:
docker compose up -dChoose stop for a temporary pause: it releases running processes while preserving the containers for start. Choose down when you want to remove the project's containers and ordinary network. Later, up -d recreates them. The example's named Redis volume survives both choices, so its counter remains available when the same project starts again.
down discards data kept only in a container's writable layer. down --volumes additionally deletes this project's Redis volume and counter; reserve it for an intentional data reset, not everyday shutdown. Keep the same project name when returning so Compose attaches the same named volume.
Docker container commands explained
stateDiagram-v2
[*] --> Created: docker create
Created --> Running: docker start
Running --> Stopped: docker stop or main process exits
Stopped --> Running: docker start
Stopped --> Removed: docker rm
Created --> Removed: docker rm
Removed --> [*]
Docker run combines creation and startup. Stop/start reuses the same container; removal discards its writable layer. Named volumes have a separate lifecycle.
The following is an alternative manual workflow using the Node image built earlier. First run docker network create demo-net. It uses host port 8081 so it can coexist with the Compose example. Names must be unused.
docker run -d --name demo-redis --network demo-net redis:7-alpine
docker run -d --name demo-web --network demo-net -p 127.0.0.1:8081:3000 -e REDIS_URL=redis://demo-redis:6379 handbook-demo:1.0
docker ps
docker ps -a
docker logs --tail 100 -f demo-web
docker exec -it demo-web sh
docker inspect demo-web
docker stats --no-stream demo-web
docker stop -t 20 demo-web
docker start demo-web
docker stop -t 20 demo-web
docker rm demo-web
docker stop demo-redis
docker rm demo-redisruncreates and starts a new container.-ddetaches,--namesets a reusable identifier, and--networkattaches it to the named network. Redis can take time to become ready; the web client retries its connection.-p 127.0.0.1:8081:3000publishes the container's port 3000 on host loopback port 8081.-esupplies a runtime environment variable.pslists running containers;ps -aalso shows stopped containers.logsreads the process's stdout and stderr.--taillimits old lines and-ffollows new lines.exec -itstarts another process in a running container with stdin open and a pseudo-terminal. It does not create a replacement container or permanently change the image.inspectreturns detailed JSON configuration and state.stats --no-streamtakes a resource-usage snapshot rather than continuously refreshing.stop -t 20sends the configured stop signal, normally SIGTERM, waits up to 20 seconds, then force-kills if necessary.startreuses the stopped container and its writable layer.rmremoves a stopped container and its writable layer. The second stop ensures demo-web is stopped before removal. The manual Redis example has no named volume; do not use it for durable data.
A container ends when its main process ends. Detaching your terminal does not turn a short-lived command into a long-running service. Changes made through exec disappear with container removal unless saved in mounted storage; rebuild images to distribute application changes.
Images & registries
docker image ls
docker pull redis:7-alpine
docker image inspect handbook-demo:1.0
docker image history handbook-demo:1.0
docker tag handbook-demo:1.0 YOUR_USER/handbook-demo:1.0
docker login
docker push YOUR_USER/handbook-demo:1.0
docker logout
docker image rm YOUR_USER/handbook-demo:1.0image ls lists local images. pull downloads a registry image, while image inspect reports metadata and image history lists build history. History is useful for size investigation, but it does not fully audit image contents.
Replace YOUR_USER with a registry namespace you own. tag creates another local reference to the same image; it does not upload or rebuild anything. login authenticates to Docker Hub by default, and push uploads the tagged image. For another registry, include its hostname in both login and the image reference. logout removes saved login credentials for that registry.
image rm removes a local image reference; it does not delete the remote image. A release tag such as 1.0 is a naming convention, not an immutability guarantee. Use digests for exact deployment identity, and deliberately update them to receive fixes.
Storage & network commands
docker volume create demo-data
docker volume inspect demo-data
docker run --rm --mount type=volume,src=demo-data,dst=/data alpine:3 sh -c 'echo hello > /data/message.txt'
docker run --rm --mount type=volume,src=demo-data,dst=/data,readonly alpine:3 cat /data/message.txt
docker network create demo-net
docker network ls
docker network inspect demo-netvolume create allocates named storage. The first temporary Alpine container writes a file through the mount; the second reads it after the writer has been removed. readonly prevents writes through that mount. volume inspect reports driver and mount metadata. A volume mounted over an existing image directory hides the underlying files while mounted.
network create creates a user-defined bridge network; skip it if demo-net already exists from the manual workflow. network ls lists networks and network inspect reports attached containers and network settings. Containers on demo-net can resolve one another by name. Publishing ports is for access from outside that network, not required for communication between its containers.
docker run --rm --mount "type=bind,src=.,dst=/work,readonly" -w /work alpine:3 lsThis bind-mount example uses a recent Docker CLI and exposes the current host directory at /work, read-only. -w chooses the process working directory. For older clients use an absolute source path. With Docker Desktop, the path must be accessible to its Linux environment. Bind mounts couple the container to host files and permissions; a writable mount lets the container modify those host files.
Cleanup & data safety
These are separate cleanup choices, not a script to run blindly. Confirm the target resources and back up data before deletion.
docker system df
docker container prune
docker image prune
docker builder prune
docker compose down --volumes
docker volume rm demo-data
docker network rm demo-netsystem dfshows Docker's disk usage before you decide what to delete.container prunedeletes all stopped containers, including their writable layers, across projects.image prunedeletes dangling images by default; adding-aalso targets images unused by containers.builder pruneremoves unused build cache. Future builds may take longer.compose down --volumesalso deletes the project's declared named volumes and attached anonymous volumes. For this example it destroys the Redis counter. External volumes are not removed by Compose down.volume rm demo-datadeletes that unused volume and its files.network rm demo-netremoves the manual network after all attached containers are removed.
Avoid adding --force just to bypass confirmation. Project-specific removal is easier to reason about than global pruning. Images, containers, caches, and volumes have separate lifecycles.
Troubleshooting
| Symptom | What to check |
|---|---|
| Cannot connect to Docker daemon | Start Docker Desktop or the engine. Inspect docker context ls and docker context show; the selected context may point to another engine. |
| Port already allocated | Inspect docker ps and host processes. Change only the host side of the mapping, for example 8083:3000. |
| Browser cannot reach web | Check compose ps and logs, the published host port, and whether the app listens on 0.0.0.0 inside its container. |
| Connection refused to localhost | Use redis:6379 from the Compose web container. Host services require an appropriate host address; Docker Desktop provides host.docker.internal. |
| Container exits immediately | Use docker ps -a, logs, and inspect. Check its command and exit status; a completed one-off task may correctly exit with status 0. |
| Unhealthy container | Inspect its health-check output. Verify the check tool exists and the endpoint works inside the container. Unhealthy does not itself trigger restart. |
| Source changes are missing | Rebuild and recreate with compose up --build -d. Check context and ignore rules. Restart alone keeps the existing image and configuration. |
| Permission denied on mounted data | Compare the container UID/GID with storage ownership. Grant the required access rather than switching indiscriminately to root or chmod 777. |
| Data appears lost | Check volume mounts and project name. A different project creates a different volume. Container removal destroys unmounted writable-layer data. |
| No matching manifest / exec format error | Check OS and CPU architecture support. A --platform choice may need emulation and does not make every binary portable. |
Security & deployment habits
- Run as a non-root user, publish only required ports, and keep base images and dependencies updated. Non-root execution is one layer of protection.
- Do not bake tokens or passwords into COPY, ARG, ENV, or command text. Use BuildKit secret mounts for build-time credentials and suitable runtime secret delivery. Compose secrets are mounted files; the application must read them.
- Keep the Docker socket and privileged mode away from untrusted workloads. Access to the daemon can grant extensive host control.
- Use read-only filesystems and reduced capabilities where the application supports them; explicitly provide required writable paths.
- Set resource limits appropriate to the workload, collect logs, and test graceful shutdown and recovery. Health checks do not replace application retries or monitoring.
- Back up persistent data with application-aware procedures and test restoration. Restart policies and volumes do not provide high availability by themselves.
Official references
- Docker getting started — installation and foundational workflows.
- Dockerfile reference — instruction syntax and build behavior.
- Compose file reference — services, networks, volumes, and secrets.
- Compose startup order — dependency ordering and readiness.
- Docker CLI reference — command flags and behavior.
- Docker volumes — persistence and volume lifecycle.