Start a container with `docker run`

docker run is the most frequently used Docker command—it creates and starts a container. Mastering its parameters means mastering the essentials of running containers.

1. What You'll Learn


2. A True Story of a Backend Developer

(1) Pain Point: Conflicts Between Multiple Database Versions

Alice needs to run three versions of PostgreSQL—v15, v14, and v13—simultaneously on her local machine to test compatibility. With the traditional installation method, she can only install one version at a time, and switching versions requires uninstalling and reinstalling, which takes 30 minutes each time. To make matters worse, the configuration files and data directories of different versions may conflict with one another.

(2) Solutions for Parallel Execution of Multiple Docker Containers

Using Docker, I started three PostgreSQL instances with a single command, each mapped to a different port.

BASH
# Run three PostgreSQL versions side by side
docker run -d --name pg15 -e POSTGRES_PASSWORD=secret -p 5432:5432 postgres:15
docker run -d --name pg14 -e POSTGRES_PASSWORD=secret -p 5433:5432 postgres:14
docker run -d --name pg13 -e POSTGRES_PASSWORD=secret -p 5434:5432 postgres:13

(3) Benefits: Multiple versions running in parallel with zero conflicts

With three PostgreSQL instances running in parallel without interfering with one another, Alice completed the cross-version compatibility testing in 5 minutes—a task that would have taken 2 hours using the traditional method.


3. docker run Syntax and Key Parameters

(1) Basic Syntax

BASH
docker run [OPTIONS] IMAGE [COMMAND] [ARG...]
Component Description Example
OPTIONS Runtime Parameters (Ports/Environment/Resources, etc.) -d -p 8080:80 --name web
IMAGE Image Name: Tag nginx:latest / postgres:15
COMMAND Override the default boot command for the image bash / sleep 3600
ARG Arguments passed to COMMAND -c "echo hello"

(2) Quick Reference Table for Common Parameters

Parameter Function Example
-d Running in the background (detached) docker run -d nginx
-it Interactive Terminal docker run -it ubuntu bash
-p Port Mapping(host:container) -p 8080:80
-P Random Port Mapping docker run -P nginx
--name Container naming --name my-app
--rm Automatically delete after logging out docker run --rm alpine echo hi
-e Set Environment Variables -e MYSQL_ROOT_PASSWORD=secret
-v Volume Mount(host:container) -v /data:/var/lib/mysql
--restart Restart Policy --restart=always
--cpus CPU limit --cpus=1.5
--memory Memory Limit --memory=256m
--network Specified Network --network=my-net
-w Working Directory -w /app
--user Running User --user 1000:1000

4. Front-End vs. Back-End Execution

Containers have two running modes: foreground and detached, which are controlled by -it and -d.

(1) Comparison of Operating Modes

Dimension Front-end Mode -it Back-end Mode -d
Terminal Occupancy Occupies Current Terminal Releases Terminal
Output Display Output directly to the terminal View using docker logs
Use Cases Interaction and Debugging Service-oriented applications (Web/DB)
How to Exit Ctrl+C or exit docker stop
Example docker run -it ubuntu bash docker run -d nginx

▶ Example: Starting the Nginx service in the background (Difficulty: ⭐)

BASH
# Run Nginx in detached mode
docker run -d -p 8080:80 --name web nginx:latest

# View logs from the background container
docker logs web
💻 Output:

TEXT
a1b2c3d4e5f6... (container ID)
/docker-entrypoint.sh: Launching nginx...

▶ Example: Launching an Interactive Ubuntu Container (Difficulty: ⭐⭐)

BASH
# Run Ubuntu with interactive terminal
docker run -it ubuntu:22.04 bash

# Inside the container: check OS info
cat /etc/os-release

# Exit the container
exit
💻 Output:

TEXT
root@a1b2c3d4e5f6:/# cat /etc/os-release
NAME="Ubuntu"
VERSION="22.04.3 LTS (Jammy Jellyfish)"
...
root@a1b2c3d4e5f6:/# exit
⚠️ Note: exit will stop the container. If you want to detach from the container but keep it running, press Ctrl+P and then Ctrl+Q (the detach shortcut).


5. Port Mapping

By default, service ports inside a container are not accessible from the outside; port mapping exposes the container's ports to the host.

100%
graph LR
    A["Host<br/>Port 8080"] -->|"-p 8080:80"| B["Container<br/>Port 80"]
    C["Host<br/>Port 5432"] -->|"-p 5432:5432"| D["Container<br/>Port 5432"]

(1) Port Mapping Policy

Method Syntax Description Example
Specified Port -p host:container Host Port → Container Port -p 8080:80
Specify Address -p ip:host:container Bind to a Specific IP -p 127.0.0.1:8080:80
Random Port -P Automatically mapped to a random port on the host -P
Range Mapping -p 8080-8090:80-90 Port Range Mapping Linux Only

▶ Example: Multi-Port Mapping for PostgreSQL (Difficulty: ⭐⭐)

BASH
# Run PostgreSQL with port mapping and environment variables
docker run -d \
  --name pg15 \
  -e POSTGRES_PASSWORD=secret \
  -e POSTGRES_DB=myapp \
  -p 5432:5432 \
  postgres:15

# Connect to PostgreSQL
docker exec -it pg15 psql -U postgres -d myapp
💻 Output:

TEXT
myapp=# \l
                                  List of databases
   Name    |  Owner   | Encoding |  Collate   |   Ctype    
-----------+----------+----------+------------+------------
 myapp     | postgres | UTF8     | en_US.utf8 | en_US.utf8
 postgres  | postgres | UTF8     | en_US.utf8 | en_US.utf8

6. Automatic Cleanup and Restart Policies

(1) --rm Temporary Container

--rm Automatically delete the container after it exits; suitable for one-time tasks.

▶ Example: Running a temporary task with --rm (Difficulty: ⭐)

BASH
# Run a one-off command, container auto-removes after exit
docker run --rm alpine:latest echo "Hello from Alpine!"

# Verify: container is gone
docker ps -a
💻 Output:

TEXT
Hello from Alpine!
💡 Tip: --rm is particularly well-suited for build tasks and temporary testing in CI/CD, helping to prevent container accumulation.

(2) Restart Policy

The restart policy determines whether a container is automatically restarted after it exits.

Strategy Behavior Applicable Scenarios
no (default) No restart Temporary task
on-failure[:max] Restart on non-zero exit (with optional limit on the number of restarts) Services that may crash sporadically
always Constantly restarts (including when the daemon restarts after being manually stopped) Core services (Web/DB)
unless-stopped Similar to "always," but will not restart after being manually stopped Services that require manual control

▶ Example: Configuring Automatic Restart (Difficulty: ⭐⭐)

BASH
# Run Nginx with restart policy
docker run -d --name web --restart=always -p 8080:80 nginx:latest

# Simulate crash: kill the container process
docker kill web

# Wait a few seconds, check: it restarted automatically
docker ps
💻 Output:

TEXT
CONTAINER ID   IMAGE          STATUS                     PORTS                  NAMES
b2c3d4e5f6a7   nginx:latest   Up 3 seconds (healthy)     0.0.0.0:8080->80/tcp   web

7. Resource Limitations

Docker can limit the amount of CPU and memory used by containers, preventing a single container from exhausting the host's resources.

(1) Resource Limit Parameters

Resource Parameters Description Example
Number of CPU Cores --cpus Maximum Number of CPU Cores Used --cpus=1.5
CPU Weight --cpu-shares Relative Weight (default 1024) --cpu-shares=512
Memory Limit --memory / -m Maximum Memory --memory=256m
Swap --memory-swap Maximum memory + Swap --memory-swap=512m

▶ Example: Limit container memory to 256MB (Difficulty: ⭐⭐)

BASH
# Run a container with 256 MB memory limit
docker run -d --name limited-app --memory=256m nginx:latest

# Verify the memory limit
docker inspect limited-app --format='{{.HostConfig.Memory}}'
💻 Output:

TEXT
268435456
⚠️ Note: 268435456 bytes = 256 MB. Containers that exceed the memory limit will be terminated by the OOM Killer (exit code 137).


8. Container Lifecycle and State Transitions

100%
stateDiagram-v2
    [*] --> Created : docker create / docker run
    Created --> Running : docker start / docker run
    Running --> Paused : docker pause
    Paused --> Running : docker unpause
    Running --> Stopped : docker stop / docker kill
    Stopped --> Running : docker start
    Running --> Restarting : crash + restart policy
    Restarting --> Running : restart succeeds
    Stopped --> Deleted : docker rm
    Running --> Deleted : docker rm -f
    Deleted --> [*]

9. Complete Example: Starting a PostgreSQL Container with Environment Variables

BASH
# ============================================
# Complete walkthrough: Run PostgreSQL with Docker
# Covers: -d, -e, -p, --name, --restart, --memory
# ============================================

# 1. Run PostgreSQL 15 with full configuration
docker run -d \
  --name pg15 \
  -e POSTGRES_USER=appuser \
  -e POSTGRES_PASSWORD=secret123 \
  -e POSTGRES_DB=appdb \
  -p 5432:5432 \
  --restart=unless-stopped \
  --memory=512m \
  postgres:15

# 2. Verify the container is running
docker ps

# 3. Connect via psql client inside the container
docker exec -it pg15 psql -U appuser -d appdb

# 4. Inside psql: create a test table
# CREATE TABLE users (id SERIAL PRIMARY KEY, name VARCHAR(100));
# INSERT INTO users (name) VALUES ('Alice'), ('Bob');
# SELECT * FROM users;

# 5. Check container resource usage
docker stats pg15 --no-stream

# 6. View container configuration
docker inspect pg15 --format='Memory: {{.HostConfig.Memory}}, RestartPolicy: {{.HostConfig.RestartPolicy.Name}}'
💻 Output (excerpt):

TEXT
# docker ps
CONTAINER ID   IMAGE         STATUS         PORTS                    NAMES
a1b2c3d4e5f6   postgres:15   Up 30 seconds  0.0.0.0:5432->5432/tcp   pg15

# docker stats --no-stream
CONTAINER ID   NAME   CPU %   MEM USAGE / LIMIT   MEM %
a1b2c3d4e5f6   pg15   0.02%   38.5MiB / 512MiB    7.52%

# docker inspect --format
Memory: 536870912, RestartPolicy: unless-stopped

❓ FAQ

Q Can -d and -it be used together?
A No. -d runs in the background, while -it is an interactive terminal; the two are mutually exclusive. If you need to run the container in the background and occasionally access it, start it with -d and then use docker exec -it to enter the container.
Q Will data be lost when the container exits?
A If you haven't used -v to mount a volume, the data will be lost when the container is deleted. The data remains after the container is stopped (stop), but it disappears after it is deleted (rm). To persist data, you must use a volume or a bind mount.
Q --rm When should it be used?
A One-time tasks: running tests, executing scripts, checking tool versions. Not suitable for services that require persistent data. --rm should be added to almost all steps in CI/CD pipelines to prevent container backlogs on build nodes.
Q -p 8080:80 Which of the two port numbers is which?
A The port on the left (8080) is the host port, and the one on the right (80) is the container port. Mnemonic: "Left is the host, right is the container." Accessing HostIP:8080 will take you to the service running on port 80 inside the container.
Q How much disk space does a container take up?
A The writable layer (the modifiable portion) of each container typically takes up only a few KB to several dozen MB. Containers do not replicate the image; instead, they share the image’s read-only layer. Total usage = image size + container’s writable layer. Use docker system df to view detailed usage.
Q How do I view all the parameters for docker run?
A docker run --help lists all the parameters. The 15 or so most commonly used ones (covered in this lesson) are listed there; refer to the rest as needed.

📖 Summary


📝 Exercises

  1. Basic Exercise (Difficulty: ⭐): Start an Nginx container mapped to port 8080 on your local machine, then access it via a browser to verify that the page displays correctly.
  2. Advanced Problem (Difficulty ⭐⭐): Launch an interactive Ubuntu container, run apt update && apt install -y curl inside the container, and then use curl to access a web page.
  3. Challenge (Difficulty: ⭐⭐⭐): With the container’s memory limited to 256MB, run a stress-testing tool (such as progrium/stress) and observe whether the container is killed by an OOM (Out of Memory) error when memory is exceeded (Hint: docker events --filter event=oom).
Web-Tutorial.com

Web-Tutorial Tech Team

A team of developers maintaining programming tutorials. Each tutorial is written and reviewed by developers with expertise in that field. We work to keep our content accurate and reliable — if you spot an issue, please let us know.

100%

🙏 帮我们做得更好

我们是刚上线的编程教程站,几个人的小团队,精力有限。页面虽经检查,难免还有疏漏——链接失效、排版错乱、内容有误、语言生硬……

如果您发现了,麻烦告诉我们,我们会在收到反馈后第一时间进行修复,再次感谢您的光临 🙏