
Docker Run
- 11 installs
- 2 repo stars
- Updated July 29, 2026
- full-statck-skills/docker-skills
Run and manage Docker containers with resource limits, health checks, restart policies, and exec/logs/inspect debugging.
About
Guides running and managing Docker containers across the full lifecycle including resource limits, health checks, and inspection. A developer uses it to run or debug individual containers.
- Full container lifecycle: create/start/stop/rm/restart with resource constraints
- Health checks, restart policies, logging drivers, and exec/inspect/stats debugging
Docker Run by the numbers
- 11 all-time installs (skills.sh)
- Ranked #993 of 1,435 DevOps & CI/CD skills by installs in the Skillselion catalog
- Data as of Jul 30, 2026 (Skillselion catalog sync)
npx skills add https://github.com/full-statck-skills/docker-skills --skill docker-runAdd your badge
Show developers this skill is listed on Skillselion. Paste this into your README.
| Installs | 11 |
|---|---|
| repo stars | ★ 2 |
| Last updated | July 29, 2026 |
| Repository | full-statck-skills/docker-skills ↗ |
What it does
Run and manage Docker containers with resource limits, health checks, restart policies, and exec/logs/inspect debugging.
Files
Docker Run — Container Lifecycle Management
Complete guidance for running, monitoring, and managing Docker containers.
When to Use
ALWAYS use this skill when the user mentions:
- "docker run", "运行容器", "启动容器"
- "docker ps", "docker stop", "docker restart"
- "容器资源限制", "memory limit", "CPU limit"
- "健康检查", "healthcheck"
- "docker logs", "查看日志"
- "docker exec", "进入容器"
- "restart policy", "容器重启策略"
Container Lifecycle
docker pull → docker create → docker start → docker run (create+start)
│
┌─────────────────────┼─────────────────────┐
▼ ▼ ▼
Running Paused/Stopped Killed
│ │
▼ ▼
docker stop docker start
docker kill docker restart
docker rm docker rm -fdocker run — Complete Reference
docker run [OPTIONS] IMAGE [COMMAND] [ARG...]
# Most common form
docker run -d --name myapp \
-p 8080:8080 \
-v /host/path:/container/path \
-e ENV_VAR=value \
--restart unless-stopped \
myimage:tag| Flag | Purpose | Example |
|---|---|---|
-d | Detached (background) | -d |
--name | Container name | --name my-nginx |
-p | Port mapping (host:container) | -p 8080:80 |
-v | Volume/bind mount | -v data:/var/lib/mysql |
-e | Environment variable | -e DB_HOST=localhost |
--env-file | Load env from file | --env-file .env |
--restart | Restart policy | --restart unless-stopped |
--rm | Auto-remove on stop | --rm (for temp containers) |
Resource Constraints
# Memory: limit + reservation
docker run --memory=512m --memory-reservation=256m myapp
# CPU: shares (relative) + cpus (absolute)
docker run --cpus=2 --cpu-shares=1024 myapp
# Combined: production-grade limits
docker run -d \
--memory=1g --memory-swap=1g \
--cpus=2 \
--pids-limit=100 \
myapp| Resource | Flag | Best Practice |
|---|---|---|
| Memory | --memory=512m | Always set; container can exhaust host memory otherwise |
| Memory+Swap | --memory-swap=1g | Set equal to memory to disable swap |
| CPU | --cpus=2 | Hard limit; --cpu-shares for relative priority |
| PIDs | --pids-limit=100 | Prevent fork bombs |
| Ulimits | --ulimit nofile=65536 | File descriptor limits |
Health Checks
Dockerfile HEALTHCHECK
HEALTHCHECK --interval=30s --timeout=3s --retries=3 \
CMD curl -f http://localhost:8080/health || exit 1Health Check States
starting → healthy (passes)
→ unhealthy (fails 3 consecutive checks)# Check health status
docker inspect --format='{{.State.Health.Status}}' myapp
# Health check in compose
# services.app.healthcheck.test: ["CMD", "curl", "-f", "http://localhost:8080/health"]Restart Policies
| Policy | Behavior | Use Case |
|---|---|---|
no | Never restart (default) | One-off tasks |
on-failure[:N] | Restart on non-zero exit, max N times | Batch jobs |
always | Always restart | Critical services (be careful — infinite loop risk) |
unless-stopped | Restart unless explicitly stopped | Recommended for most services |
docker run --restart unless-stopped myapp
docker update --restart always myapp # Change policy on running containerLogging & Debugging
# View logs
docker logs myapp # All logs
docker logs -f myapp # Follow (tail -f)
docker logs --tail 50 myapp # Last 50 lines
docker logs --since 10m myapp # Last 10 minutes
# Execute commands in container
docker exec -it myapp sh # Interactive shell
docker exec myapp cat /etc/hosts # Run single command
# Inspect state
docker inspect myapp # Full JSON metadata
docker stats myapp # Live resource usage
docker top myapp # Running processes
docker port myapp # Port mappingsSignal Handling
docker stop myapp → SIGTERM → wait 10s → SIGKILL
docker kill myapp → SIGKILL immediately
docker kill -s HUP myapp → Send custom signal| Signal | docker command | Container effect |
|---|---|---|
| SIGTERM | docker stop | Graceful shutdown (default) |
| SIGKILL | docker kill | Force kill (no cleanup) |
| SIGHUP | docker kill -s HUP | Reload config (app-specific) |
Workflow — 推荐操作流程
Step 1: 拉取或构建镜像: docker pull 或 docker build 准备好镜像 Step 2: 运行容器: docker run -d --name myapp -p 8080:8080 -v data:/data --memory 512m myapp Step 3: 验证启动: docker ps + docker logs myapp 确认运行正常 Step 4: 配置健康检查: 确保 HEALTHCHECK 在 Dockerfile 中定义或运行时指定 Step 5: 监控运行: docker stats + docker logs -f 持续观察
Gotchas — Common Pitfalls
- Default `--memory=0` (unlimited): Container can consume all host memory. → Recovery:
docker run --memory=512m --cpus=1 app; check usage withdocker stats. - `docker stop` timeout: Default 10s grace period. → Recovery:
docker stop -t 30 myapp; ensure app handles SIGTERM properly. - `docker run` creates new container: Running
docker run nginxtwice creates two containers. → Recovery:docker start <existing-name>to restart;docker ps -ato find stopped containers. - Logs filling disk: JSON-file driver has no rotation by default. → Recovery:
docker run --log-opt max-size=10m --log-opt max-file=3 app; existing containers: edit/etc/docker/daemon.json+ restart dockerd. - `docker exec` exit codes: Returns the command's exit code. → Recovery: Use for scripting:
docker exec myapp healthcheck.sh || exit 1.
Boundary — 能力边界(适用与不适用场景)
| 分类 | 场景 | 说明 |
|---|---|---|
| ✅ 能做 | docker run 运行容器 | 所有参数、资源限制、重启策略 |
| ✅ 能做 | 健康检查配置 | HEALTHCHECK 指令 + 运行时覆盖 |
| ✅ 能做 | 日志管理 | 日志驱动选择 + 轮转配置 |
| ✅ 能做 | 进入容器调试 | docker exec / docker attach |
| ⚠️ 需条件 | --privileged 特权模式 | 仅调试用,生产禁止 |
| ⚠️ 需条件 | 修改运行中容器限制 | 需 docker update,部分参数不可动态改 |
| ❌ 超范围 | 编写 Dockerfile | 使用 docker-dockerfile |
| ❌ 超范围 | 多容器编排 | 使用 docker-compose |
| ❌ 超范围 | 镜像构建 | 使用 docker-build |
When NOT to Use This Skill
| ❌ Skip | ✅ Use Instead |
|---|---|
| Docker basics / first-time setup | docker-basics |
| Writing Dockerfile | docker-build |
| Multi-container apps | docker-compose |
| Network configuration | docker-networking |
| Storage/Volume management | docker-storage |
Security & Stability
- Always set
--memoryand--cpuslimits in production to prevent noisy-neighbor issues. - Avoid
--privilegedflag. Use specific--cap-addinstead. - Never run containers as root. Use
--userflag orUSERin Dockerfile. - Use
--read-onlyfor stateless containers where possible. - No executable scripts bundled. Guidance only.
📚 官方文档参考
| 文档 | 地址 |
|---|---|
| Docker 引擎 | https://docs.docker.com/engine/ |
| docker run 参考 | https://docs.docker.com/reference/cli/docker/container/run/ |
| 容器管理 CLI | https://docs.docker.com/reference/cli/docker/container/ |
| 运行时选项 | https://docs.docker.com/engine/reference/run/ |
| 资源限制 | https://docs.docker.com/config/containers/resource_constraints/ |
| 日志驱动 | https://docs.docker.com/config/containers/logging/ |
🧭 Docker Skills Journey
📍 You are here: `docker-run` — Step 3: 容器管理与运维
← Previous: docker-build — Dockerfile & 镜像构建 → Next: docker-networking / docker-storage / docker-compose
docker run 基础使用
# 基本运行
docker run nginx:alpine # 前台运行
# 后台运行 + 命名
docker run -d --name web nginx:alpine # -d 后台, --name 命名
# 端口映射
docker run -d -p 8080:80 nginx:alpine # host:container
docker run -d -p 127.0.0.1:8080:80 nginx:alpine # 仅 localhost
docker run -d -p 8080:80/udp nginx:alpine # UDP
# 卷挂载
docker run -d -v /data:/var/lib/mysql mysql:8.4 # bind mount
docker run -d -v myvolume:/data alpine # named volume
docker run -d -v /var/run/docker.sock:/var/run/docker.sock ...
# 环境变量
docker run -d -e NODE_ENV=production -e PORT=3000 node:22-alpine
docker run -d --env-file .env myapp
# 重启策略
docker run -d --restart always nginx:alpine
docker run -d --restart on-failure:5 myapp
docker run -d --restart unless-stopped myapp
# 资源限制
docker run -d --memory 512m --cpus 1.0 myapp
docker run -d --memory 256m --memory-swap 512m myapp
# 常用组合
docker run -d \
--name myapp \
--restart unless-stopped \
-p 8080:8080 \
-v app_data:/data \
-e NODE_ENV=production \
--memory 512m --cpus 0.5 \
myapp:latest
# 容器管理
docker ps # 运行中
docker ps -a # 全部
docker logs -f myapp # 跟踪日志
docker logs --tail 50 myapp # 最后 50 行
docker exec -it myapp sh # 进入容器
docker stop myapp # 停止
docker start myapp # 启动已停止的
docker restart myapp # 重启
docker rm myapp # 删除
docker rm -f myapp # 强制删除
Container with health check
FROM nginx:alpine
COPY default.conf /etc/nginx/conf.d/
HEALTHCHECK --interval=30s --timeout=3s --retries=3 CMD wget -qO- http://localhost/health || exit 1docker build -t nginx-health .
docker run -d --name web nginx-health
# Watch health status change: starting → healthy
watch docker inspect --format='{{.State.Health.Status}}' web
# Simulate unhealthy: kill nginx inside
docker exec web nginx -s stop
# After 3 failed checks → unhealthyProduction-grade resource limits
docker run -d --name app --memory=512m --memory-swap=512m \ # Hard limit, no swap
--memory-reservation=256m \ # Soft limit for scheduler
--cpus=2 \ # Max 2 CPU cores
--cpu-shares=1024 \ # Relative weight (default 1024)
--pids-limit=100 \ # Prevent fork bombs
--ulimit nofile=65536:65536 \ # Max open files
--read-only \ # Read-only root filesystem
--tmpfs /tmp:rw,noexec,nosuid \ # Writable /tmp in RAM
myapp:1.0.0Restart Policies
| Policy | Behavior | Recommended For |
|---|---|---|
no (default) | Never restart | One-off jobs, batch tasks |
on-failure[:N] | Restart on non-zero exit, max N times | Batch jobs with retry |
always | Always restart (even after daemon restart) | ⚠️ Use with caution — infinite loop risk |
unless-stopped | Restart unless explicitly stopped | Most services (recommended) |
# Set at run time
docker run --restart unless-stopped myapp
# Change on running container
docker update --restart always myappdocker run 完整参数速查
容器生命周期
| 命令 | 说明 |
|---|---|
docker create | 创建但不启动 |
docker start | 启动已创建的容器 |
docker run | create + start |
docker stop | 优雅停止(SIGTERM→SIGKILL) |
docker kill | 立即停止(SIGKILL) |
docker restart | stop + start |
docker pause/unpause | 暂停/恢复(cgroup freezer) |
docker rm | 删除已停止容器 |
docker rm -f | 强制删除(运行中也删) |
docker run 完整参数
| 参数 | 说明 | 示例 |
|---|---|---|
-d, --detach | 后台运行 | -d |
--name | 容器名称 | --name web |
-p, --publish | 端口映射 | -p 8080:80 |
-P | 映射所有 EXPOSE 端口(随机) | -P |
-v, --volume | 卷挂载 | -v /host:/container:ro |
--mount | 更详细的挂载语法 | --mount type=bind,src=... |
-e, --env | 环境变量 | -e NODE_ENV=prod |
--env-file | 从文件加载环境变量 | --env-file .env |
-w, --workdir | 工作目录 | -w /app |
-u, --user | 运行用户 | -u 1000:1000 |
--restart | 重启策略 | --restart unless-stopped |
--memory | 内存限制 | --memory 512m |
--cpus | CPU 限制 | --cpus 1.5 |
--network | 网络 | --network mynet |
--hostname | 主机名 | --hostname app1 |
--add-host | 添加 hosts 条目 | --add-host db:192.168.1.100 |
--dns | DNS 服务器 | --dns 8.8.8.8 |
--link | 链接容器(已废弃) | --link redis:redis |
--rm | 退出后自动删除 | --rm |
-i, --interactive | 保持 STDIN 打开 | -i |
-t, --tty | 分配伪终端 | -t |
--read-only | 根文件系统只读 | --read-only |
--tmpfs | tmpfs 挂载 | --tmpfs /tmp:rw,size=128M |
--cap-add/--cap-drop | 添加/移除 Linux capabilities | --cap-drop=ALL |
--security-opt | 安全选项 | --security-opt no-new-privileges |
--label | 元数据标签 | --label env=prod |
--log-driver | 日志驱动 | --log-driver json-file |
--log-opt | 日志驱动选项 | --log-opt max-size=10m |
--health-cmd | 覆盖 HEALTHCHECK | --health-cmd "curl -f localhost" |
--health-interval | 健康检查间隔 | --health-interval 30s |
--init | 使用 init 进程(tini) | --init |
--privileged | 特权模式(慎用) | --privileged |
重启策略
| 策略 | 行为 |
|---|---|
no | 不自动重启(默认) |
on-failure[:N] | 仅退出码非 0 时重启,最多 N 次 |
always | 总是重启(包括 daemon 重启后) |
unless-stopped | 除非手动 stop,否则重启 |
Logging Drivers
| Driver | Where Logs Go | Rotation? | Use Case |
|---|---|---|---|
json-file (default) | Host disk | Manual (--log-opt) | Development |
syslog | Syslog daemon | System | Centralized logging |
journald | journald | System | systemd-based systems |
fluentd | Fluentd | Agent | ELK/Loki stack |
awslogs | CloudWatch | AWS | AWS ECS |
gcplogs | Stackdriver | GCP | GKE |
# Production log rotation (json-file)
docker run --log-opt max-size=10m --log-opt max-file=3 myapp
# Daemon-level: /etc/docker/daemon.json
{ "log-driver": "json-file", "log-opts": { "max-size": "10m", "max-file": "3" } }健康检查模式库
内置 HEALTHCHECK
# HTTP 检查
HEALTHCHECK --interval=30s --timeout=3s --start-period=10s --retries=3 \
CMD curl -f http://localhost:8080/health || exit 1
# TCP 检查
HEALTHCHECK --interval=10s --timeout=3s \
CMD nc -z localhost 3306 || exit 1
# 进程检查
HEALTHCHECK --interval=30s --timeout=3s \
CMD pgrep nginx || exit 1
# 自定义脚本
HEALTHCHECK --interval=30s --timeout=3s \
CMD /app/health-check.sh || exit 1运行时覆盖
docker run -d \
--health-cmd="curl -f http://localhost:8080/health || exit 1" \
--health-interval=10s \
--health-timeout=3s \
--health-start-period=30s \
--health-retries=3 \
myapp参数说明
| 参数 | 默认 | 说明 |
|---|---|---|
--interval | 30s | 检查间隔 |
--timeout | 30s | 单次检查超时 |
--start-period | 0s | 启动宽限期(不计数失败) |
--start-interval | 5s | 启动期间检查间隔(v25+) |
--retries | 3 | 连续失败次数阈值 |
状态查看
docker inspect --format='{{.State.Health.Status}}' myapp
# healthy / unhealthy / starting
docker inspect --format='{{json .State.Health}}' myapp | jq .按场景的推荐配置
| 场景 | interval | timeout | retries | start-period |
|---|---|---|---|---|
| Web API | 30s | 3s | 3 | 10s |
| 数据库 | 10s | 5s | 5 | 30s |
| 消息队列 | 15s | 5s | 5 | 20s |
| 批处理 | 60s | 10s | 2 | 5s |
| 缓存 | 10s | 3s | 3 | 5s |
Compose 中依赖健康检查
services:
api:
depends_on:
db:
condition: service_healthy # 等待 db 健康再启动
healthcheck:
test: ["CMD", "curl", "-f", "http://localhost:8080/health"]
interval: 15s
timeout: 3s
retries: 3