DevOpsLesson
DevOpsLesson

Free, comprehensive DevOps tutorials and learning roadmaps. Master Docker, Kubernetes, CI/CD, and more.

Stay Updated

Get notified about new tutorials and features.

Tutorials

  • What is DevOps?
  • Docker Tutorial
  • Terraform Tutorial
  • CI/CD Pipeline
  • All Tutorials

Roadmaps

  • DevOps Engineer
  • Cloud Engineer
  • SRE Path
  • All Roadmaps

Company

  • About Us
  • Blog
  • Contact
  • Privacy Policy
  • Terms of Service

© 2026 DevOpsLesson. All rights reserved.

DOCKERKUBERNETESTERRAFORMAWSCI/CDLINUXGITDEVOPS ROADMAPCLOUD ROADMAPSRE ROADMAPGIT CHEATSHEETDOCKER CHEATSHEETK8S CHEATSHEETTF CHEATSHEETLINUX CHEATSHEETDOCKERFILE LINTERYAML VALIDATORCRON PARSERREGEX TESTER

Docker Tutorial

Introduction to docker
Why Use Docker?
Docker vs Virtual Machines
Installing Docker
Key Docker Concepts
Docker Images
Docker Containers
Writing Dockerfiles
Docker Volumes

Running Containers

PreviousPrev
Next

Master docker run - the most important Docker command. Learn every essential flag for port mapping, naming, detached mode, and more.

Docker Run Command

After creating image, we run the image and make container out of it.


The Basic Syntax

docker run [OPTIONS] IMAGE [COMMAND] [ARGS...]

At its most basic:

docker run hello-world

This one command does a lot: it checks if the hello-world image exists locally, if doesn't exists then pulls it from Docker Hub, creates a container from it, runs it, prints a message, and exits. That's the magic of docker run. It handles the entire lifecycle in one step.


Detached vs. Interactive Mode

The first decision you make with almost every docker run is whether you want to interact with the container or let it run in the background.

Running in the Background (-d)

Most services like web servers, databases, APIs, should run detached so they don't tie up your terminal:

docker run -d nginx
# Returns: a3f8c2d1b4e9...  (the container ID)

The container starts and keeps running after the command returns. You get your terminal back immediately. Check that it's running with docker ps.

Running an Interactive Shell (-it)

When you want to explore a container, run commands inside it, or debug something, use -it to open an interactive session:

# Open a bash shell inside Ubuntu
docker run -it ubuntu bash

-i keeps the input stream open so you can type commands. -t allocates a terminal so things like prompts and colors work properly. You almost always use them together as -it.

Auto-Remove When Done (--rm)

For one-off tasks like running a script, checking a tool's version, quick tests, you don't want the container sitting around as a stopped container afterward. --rm takes care of that automatically:

# Container disappears the moment it finishes
docker run --rm alpine echo "Hello!"
docker run --rm python:3.12 python -c "print(2 ** 10)"

Without --rm, every container you run sticks around in a stopped state until you manually clean it up. Over time this clutters your system with dozens of stopped containers you'll never use again.


Naming Your Container

By default, Docker makes up a random two-word name like admiring_lovelace or jolly_tesla. These are fun but useless when you need to manage the container later.

Use --name to give your container a meaningful name:

docker run -d --name web-server nginx
docker run -d --name my-db postgres:16

One rule: names must be unique. If a container named my-db already exists (even if stopped), Docker will refuse to create another one with the same name.


Port Mapping

Containers run in their own isolated network. If you run nginx inside a container, you can't just visit localhost:80 on your host machine, the ports aren't connected yet.

Port mapping is how you bridge that gap. The format is -p hostPort:containerPort:

# Forward host port 8080 to container port 80
docker run -d -p 8080:80 nginx

Now http://localhost:8080 on your machine sends traffic to port 80 inside the container.

More examples to cover common scenarios:

# Only accessible from your own machine (not the network)
docker run -d -p 127.0.0.1:5432:5432 postgres:16

# Expose multiple ports at once
docker run -d -p 8080:80 -p 8443:443 nginx

# Let Docker pick a random available host port
docker run -d -p 80 nginx
docker port <container-id>   # Check which port was assigned

# Automatically map all ports the image declared with EXPOSE
docker run -d -P nginx

A common beginner mistake: mapping ports backwards. Remember: host port first, container port second. -p 8080:80 means "my machine's port 8080 goes to the container's port 80."


Overriding the Default Command

Every image has a default command baked in (set by CMD in the Dockerfile). You can replace it by adding a command at the end of docker run:

# Default: nginx runs its web server
docker run nginx

# Override: open a shell instead
docker run -it nginx bash

# Run a specific Python script
docker run python:3.12 python my_script.py

# Pass flags to the application
docker run redis:7 redis-server --maxmemory 256mb

This is useful for exploring what's inside an image, running one-off scripts, or testing different startup configurations.


Setting a Working Directory

Use -w to set which directory the container starts in:

docker run -it -w /app node:20-alpine sh
# You'll land directly in /app instead of the root directory

Resource Limits

On a shared machine or in production, you don't want a single container consuming all available memory or CPU. Set limits explicitly:

# Cap memory at 512MB
docker run -d --memory 512m nginx

# Limit to half a CPU core
docker run -d --cpus 0.5 nginx

# Both limits together
docker run -d --memory 256m --cpus 0.25 --name limited-app myapp:latest

Without limits, a memory leak or traffic spike in one container can starve every other process on the host. It's a good habit to always set these for services running in production.


Restart Policies

What should Docker do if your container crashes, or if the host machine reboots? That's what --restart controls:

# Do nothing on exit (the default)
docker run --restart no nginx

# Restart only if the container crashes (exits with a non-zero code)
docker run --restart on-failure nginx

# Restart unless you explicitly stop it
docker run --restart unless-stopped nginx

# Always restart, even after a manual docker stop
docker run --restart always nginx

unless-stopped is the right choice for most production services. It means your container survives host reboots automatically, but respects it when you intentionally stop it with docker stop.


Hands-On Practice: Run a Named Container with Port Mapping

# Step 1: Run nginx in the background, named, with port mapping
docker run -d --name my-web -p 8080:80 nginx

# Step 2: Confirm it's running
docker ps

# Step 3: Visit it in your browser or test with curl
curl http://localhost:8080

After step 1, you should see a container ID printed. After step 2, you'll see my-web listed as running with 0.0.0.0:8080->80/tcp in the ports column. That confirms the port mapping is active.


Listing Containers

Once containers are running, these are the commands you'll use to check on them:

# Show currently running containers
docker ps

# Show all containers including stopped ones
docker ps -a

# Show only container IDs (useful for scripting)
docker ps -q

# Custom formatted output
docker ps --format "table {{.Names}}\t{{.Status}}\t{{.Ports}}"

Key Takeaways

  • -d runs in the background so you get your terminal back. -it opens an interactive shell for exploration.
  • --rm auto-deletes the container when it exits. It is used for one-off commands to avoid clutter.
  • --name makes containers much easier to manage. Always name containers you plan to keep.
  • -p hostPort:containerPort connects your machine's ports to the container's ports. Host port first, container port second.
  • --restart unless-stopped is the right policy for most production services where it survives reboots, respects manual stops.
  • Always set --memory and --cpus limits on shared hosts to prevent one container from starving the rest.

Frequently Asked Questions

What's the difference between docker run and docker start?

docker run creates a brand new container from an image and starts it. docker start restarts an existing container that was previously stopped. You use docker run the first time, and docker start to resume it later.

If I use -d, how do I see what the container is doing?

Use docker logs <container-name> to see its output. Add -f to follow the logs in real time, just like tail -f. For example: docker logs -f my-web.

What happens to a container when it finishes running?

By default it stops and sits in a "stopped" state, and you can see it with docker ps -a. It stays there until you remove it with docker rm. If you used --rm, it's deleted automatically the moment it exits.

Can two containers use the same host port?

No. Only one process on your machine can listen on a given port at a time. If you try to run two containers both mapped to port 8080, the second one will fail with a "port already in use" error.

What does -p 127.0.0.1:5432:5432 do differently from -p 5432:5432?

-p 5432:5432 binds to all network interfaces, and anyone on your network could potentially reach it. -p 127.0.0.1:5432:5432 binds only to your loopback interface, meaning only your own machine can connect. For databases, always use the 127.0.0.1 form unless you specifically need network access.

What's the difference between --restart always and --restart unless-stopped?

Both restart automatically after a host reboot. The difference is what happens after a manual docker stop. With unless-stopped, a manual stop is respected, and the container stays stopped. With always, Docker will restart it again even after you stop it manually, which can be surprising and hard to control.

PreviousPrev
Next

Continue Learning

Optimization

Practical techniques to shrink Docker image sizes, speed up builds, and harden images for production use.

9 min·Easy

Managing Images

Learn to tag, remove, save, load, and push Docker images, keeping your local environment clean and your registry organized.

7 min·Easy

Docker Containers

Learn the complete lifecycle of Docker containers - create, run, inspect, manage, and clean them up. The hands-on foundation for everything else in Docker.

30 min·Easy

Explore Related Topics

Ku

Kubernetes Tutorials

Orchestrate your Docker containers at scale

CI

CI/CD Tutorials

Automate Docker builds and deployments in pipelines

Try the Tool

Dockerfile Linter

Instantly lint your Dockerfile for best-practice violations and security issues.

On This Page

The Basic SyntaxDetached vs. Interactive ModeRunning in the Background (`-d`)Running an Interactive Shell (`-it`)Auto-Remove When Done (`--rm`)Naming Your ContainerPort MappingOverriding the Default CommandSetting a Working DirectoryResource LimitsRestart PoliciesHands-On Practice: Run a Named Container with Port MappingListing ContainersKey TakeawaysFrequently Asked Questions