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
- Key parameters of
docker run - Front-end vs. Back-end Operation Modes
- Port mapping mechanism
- Container Naming and Automatic Cleanup
- Resource limitations (CPU/memory)
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.
# 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
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: ⭐)
# Run Nginx in detached mode
docker run -d -p 8080:80 --name web nginx:latest
# View logs from the background container
docker logs web
a1b2c3d4e5f6... (container ID)
/docker-entrypoint.sh: Launching nginx...
▶ Example: Launching an Interactive Ubuntu Container (Difficulty: ⭐⭐)
# 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
root@a1b2c3d4e5f6:/# cat /etc/os-release
NAME="Ubuntu"
VERSION="22.04.3 LTS (Jammy Jellyfish)"
...
root@a1b2c3d4e5f6:/# exit
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.
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: ⭐⭐)
# 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
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: ⭐)
# 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
Hello from Alpine!
--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: ⭐⭐)
# 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
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: ⭐⭐)
# 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}}'
268435456
8. Container Lifecycle and State Transitions
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
# ============================================
# 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}}'
# 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
-d and -it be used together?-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.-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.--rm When should it be used?--rm should be added to almost all steps in CI/CD pipelines to prevent container backlogs on build nodes.-p 8080:80 Which of the two port numbers is which?HostIP:8080 will take you to the service running on port 80 inside the container.docker system df to view detailed usage.docker run?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
docker run= Create and start a container; this is the most essential Docker command-dRuns as a background service;-itInteractive debugging; the two are mutually exclusive- Port Mapping
-p host:containerExposes Container Services to the Host --rmis used for automatic cleanup of temporary tasks;--restartis used for automatic service recovery--memory/--cpusLimit resources to prevent a single container from using up all the host's resources- Containers have a complete state lifecycle: Created → Running → Paused → Stopped → Deleted
📝 Exercises
- 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.
- Advanced Problem (Difficulty ⭐⭐): Launch an interactive Ubuntu container, run
apt update && apt install -y curlinside the container, and then usecurlto access a web page. - 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).



