SyntaxStudy
Sign Up
Docker Running and Managing Containers
Docker Beginner 1 min read

Running and Managing Containers

docker run is the primary command for creating and starting containers. The most important flags are -d (detached/background mode), -p host:container (port mapping), --name (assign a name), --rm (auto-remove on exit), -e (set environment variable), and -v (mount a volume). Combining them correctly is the foundation of all Docker workflows. A container's lifecycle is: created, running, paused, stopped, removed. docker stop sends SIGTERM and waits 10 seconds before sending SIGKILL; this grace period allows the application to shut down cleanly. docker kill sends SIGKILL immediately. docker rm removes a stopped container; docker rm -f forces removal of a running container. Restart policies (--restart always, --restart unless-stopped, --restart on-failure:3) control what happens when a container exits. unless-stopped is the most practical for long-running services: it restarts on crash or host reboot but respects a deliberate docker stop.
Example
# Run a web server (detached, named, port-mapped)
docker run -d \
  --name api \
  -p 3000:3000 \
  -e NODE_ENV=production \
  -e DATABASE_URL=postgres://user:pass@db:5432/mydb \
  --restart unless-stopped \
  myapp:2.1.0

# Verify it started
docker ps
docker logs api --tail 20 --follow

# Run a one-off command (auto-removed after exit)
docker run --rm node:20-alpine node -e "console.log(process.version)"

# Interactive shell in a new container
docker run -it --rm ubuntu:24.04 bash

# Stop / start / restart
docker stop api
docker start api
docker restart api

# View all containers including stopped
docker ps -a

# Remove containers
docker rm api
docker rm -f api   # force-remove running container

# Custom listing format
docker ps --format "table {{.ID}}\t{{.Image}}\t{{.Status}}\t{{.Ports}}"