Master Docker Commands for Container Management

Docker commands. You’ll need them. Every single day. The problem isn’t learning Docker. The problem is remembering which command does what when you’re three deploys deep and your production environment is burning. This guide breaks down the commands you’ll actually use, organized by what they do instead of alphabetically because that’s how your brain works under pressure.

Commands fall into multiple categories: build & manage images, clean up the mess, start and stop containers, check what’s running. Also configure containers, push to registries, orchestrate services, set up networks. Let’s get into it.

Docker Build Commands

The docker build command turns your Dockerfile into an image. That’s it. Everything else is just options.

Build from your current directory with docker build. Want to tag it so you can find it later? Add -t imagename/tag. The tag isn’t optional if you plan to push to a registry.

You can build from remote sources too. Point at a Git repo with docker build https://github.com/user/repo.git#branch:folder. Or grab a tar archive from your server with docker build https://yourserver/file.tar.gz.

Need to skip the cache? Use --no-cache. Pass build arguments with --build-arg KEY=value. These show up in your Dockerfile as ARG variables.

The build process reads your Dockerfile line by line. Each instruction creates a layer. Layers get cached. That’s why your first build takes forever and subsequent builds finish in seconds. Unless you change something near the top of the Dockerfile. Then everything below that line rebuilds.

Docker Prune and Cleanup Commands

Docker fills your disk. Fast. Dangling images, stopped containers, unused volumes. They pile up.

Run docker system prune to clear stopped containers, unused networks, dangling images, and build cache. Add -a to remove all unused images, not just dangling ones. This frees up gigabytes.

For targeted cleanup, use docker image prune to delete untagged images. Clear volumes with docker volume rm $(docker volume ls -f dangling=true -q). Remove specific images with docker image rm imagename.

Want to nuke everything? Stop all running containers with docker kill $(docker ps -q), then remove them with docker rm $(docker ps -a -q). Don’t do this in production.

Schedule prune commands in your deployment pipeline. Your DevOps team will thank you when they’re not hunting down disk space at 2 AM.

Managing Containers: Start, Stop, and Restart

Container lifecycle management. Start, stop, pause, restart. These commands control what’s running.

Use docker start containername to fire up a stopped container. Stop it with docker stop containername. Restart with docker restart containername. Simple.

Need to freeze a container temporarily? docker pause containername suspends all processes. Resume with docker unpause containername. The container’s state persists in memory.

Stopping all containers at once requires a command chain. docker stop $(docker ps -q) stops everything currently running. The -q flag outputs only container IDs.

Set restart policies when you launch containers. Use --restart=always for services that should survive system reboots. Or --restart=on-failure to restart only after crashes.

Docker Logs and Container Inspection

Something broke. You need logs.

Run docker logs containername to dump everything the container wrote to stdout and stderr. Add -f to follow logs in real-time. Use --tail 100 to see just the last 100 lines.

List running containers with docker ps. See everything, including stopped containers, with docker ps -a. The output shows container IDs, images, commands, status, and ports.

Dig deeper with docker inspect containername. This dumps a JSON blob containing every detail: network settings, mounts, environment variables, resource limits. Pipe it to grep or jq to find what you need.

Check resource usage with docker stats. It shows CPU percentage, memory usage, network I/O, and block I/O for each running container. Watch it stream live or capture a snapshot.

See what changed in a container’s filesystem? docker diff containername lists added, deleted, and modified files. Useful for debugging containers that modify their own filesystems.

Docker Images Management

Images are templates. Containers are running instances. Managing images means keeping your local repository clean and tagged correctly.

List all images with docker images or docker image ls. You’ll see repository names, tags, image IDs, creation dates, and sizes. Filter by name with docker images imagename.

Tag images with docker tag source target. This creates a new reference to the same image. Common pattern: docker tag myapp:latest myapp:v1.2.3. Now you’ve got a version-specific tag and a latest tag pointing to the same image.

Remove images with docker image rm imagename or docker rmi imagename. Delete multiple images by listing them: docker rmi image1 image2 image3.

Check image history with docker history imagename. Each line shows a layer: the command that created it, when it was created, and how much disk space it uses. Bloated images? This shows you where.

Prune unused images with docker image prune. Add -a to remove all images not referenced by any container. This isn’t reversible, so don’t get trigger-happy on your build server.

Docker Run Command Options

The docker run command creates and starts a container from an image. One command, dozens of flags.

Basic syntax: docker run imagename. This runs the container in the foreground and blocks your terminal. Add -d to detach and run it in the background.

Name your container with --name containername. Otherwise Docker generates random names like ‘quirky_tesla’ that you’ll never remember. Map ports with -p hostport:containerport. Example: -p 8080:80 maps container port 80 to host port 8080.

Set environment variables with -e KEY=value. Mount volumes using -v /host/path:/container/path. Make the container filesystem read-only with --read-only for security.

Auto-remove containers when they stop with --rm. Perfect for one-off tasks. Connect to specific networks using --network networkname. Set resource limits with --memory and --cpus.

Interactive mode requires two flags: -i keeps stdin open and -t allocates a pseudo-TTY. Combine them as -it for shell access: docker run -it ubuntu bash.

Docker Hub and Registry Commands

Docker Hub hosts millions of images. Your private registry might host yours. Either way, you need to pull, push, and authenticate.

Log in with docker login. It prompts for username and password. For automated systems, pass credentials via stdin or use access tokens. Log out with docker logout.

Pull images from Docker Hub with docker pull imagename. Specify tags like docker pull nginx:1.21. Without a tag, it defaults to latest. That’s often not what you want in production.

Push images with docker push username/imagename:tag. The image name must include your Docker Hub username or your registry URL. Tag it correctly before pushing or it’ll fail.

Search Docker Hub from the command line using docker search searchterm. It returns official images, automated builds, and star counts. The web interface gives you more details though.

For private registries, prefix image names with the registry URL: registry.example.com/imagename. Login, pull, and push work the same way. Just point at a different registry.

Docker Swarm Service Management

Docker Swarm orchestrates containers across multiple hosts. Services define how your containers should run in the swarm.

List services with docker service ls. This shows service names, modes, replicas, images, and ports. For detailed info about a specific service, run docker service ps servicename.

Create a service with docker service create. Example: docker service create --name web --replicas 3 -p 80:80 nginx. This deploys three nginx replicas across your swarm.

Scale services up or down with docker service scale servicename=5. Swarm handles distributing the replicas. Update running services using docker service update with flags like --image for rolling updates.

Check service logs with docker service logs servicename. This aggregates logs from all replicas. Deploy entire stacks using docker stack deploy with a compose file.

Kubernetes won the orchestration war. But Swarm’s still simpler for smaller deployments. No learning curve. Just works.

Docker Network Configuration

Containers need to talk to each other and the outside world. Networks make that happen.

List networks with docker network ls. You’ll see bridge, host, and none by default. Create custom networks using docker network create networkname. Specify drivers with --driver bridge or --driver overlay for swarm.

Connect running containers to networks with docker network connect networkname containername. Disconnect with docker network disconnect. Containers can belong to multiple networks.

The bridge network is default. Containers on the same bridge network can reach each other by name. Host network mode gives containers direct access to the host’s network stack. Use --network host when launching containers that need maximum network performance.

Inspect network details with docker network inspect networkname. This shows connected containers, IP addresses, subnet configuration, and gateway settings. Remove unused networks with docker network rm networkname.

Custom networks give you DNS resolution between containers. That’s why you create them instead of using the default bridge. Name resolution beats hardcoding IP addresses.

Docker Tutorial and Best Practices

Commands are one thing. Using them correctly is another.

  • Start with the basics. Install Docker. Run docker run hello-world. If that works, you’re set. Build a simple Dockerfile. Create an image. Run a container. Break things. Fix them.
  • Keep images small. Each layer adds size. Combine RUN commands. Clean up package caches in the same layer where you install them. Use multi-stage builds to separate build dependencies from runtime dependencies.
  • Don’t run containers as root. Create a user in your Dockerfile with RUN useradd. Switch to it with USER username. Security matters even in containers.
  • Tag your images properly. Use semantic versioning. Never rely on latest in production. Pin exact versions in your deployment configs. When an image updates and breaks your app, you’ll understand why.
  • Monitor resource usage. Set memory limits with --memory. Cap CPU with --cpus. A container consuming all available resources takes down the entire host.
  • Use health checks. Add HEALTHCHECK instructions to your Dockerfile. Docker can then automatically restart unhealthy containers. Better than waiting for your monitoring system to page you.
  • Store secrets properly. Don’t bake them into images. Don’t pass them as environment variables that show up in docker inspect. Use Docker secrets for swarm or external secret management tools.

The commands in this guide cover 90% of daily Docker work. The other 10%? That’s where you read the docs, search GitHub issues, and piece together solutions from Stack Overflow. Welcome to containerization!

Scroll to Top