Docker Hello World
跑通第一个容器,理解 run 的常用参数与容器生命周期。
Key Pointsdocker run 的参数决定容器怎么跑:-d 后台、-it 交互、--name 命名、--rm 退出即删、-p 端口映射。
第一个容器
Bash
docker run ubuntu:24.04 /bin/echo "Hello world"Text
Unable to find image 'ubuntu:24.04' locally
24.04: Pulling from library/ubuntu
Hello worldFull meaning: create a container from ubuntu:24.04, run /bin/echo "Hello world" inside it, and exit as soon as the command finishes.
交互式容器
Bash
docker run -it ubuntu:24.04 /bin/bash
# 现在你在容器里的 shell,exit 退出-i保持标准输入打开-t分配一个伪终端(有提示符、支持颜色)- 两个一起用才像本地终端:
-it
后台运行
Bash
docker run -d --name web -p 8080:80 nginx
docker ps
docker logs -f web
docker exec -it web bash
docker stop web && docker rm web| Flag | Meaning |
|---|---|
-d | Detached — run in background, print the container id |
--name | Give it a name instead of a random one |
-p 8080:80 | Map host port 8080 to container port 80 |
-v host:container | Mount a directory or volume |
-e KEY=VALUE | Set an environment variable |
--rm | Delete the container when it exits |
--restart always | Restart on crash and on boot |
容器为什么立刻退出了
A container lives as long as its main process. docker run -d ubuntu has no foreground process, so it exits immediately — the classic beginner trap. Keep it alive with a foreground process (nginx -g 'daemon off;', tail -f /dev/null).
Bash
docker run -d --name sleeper ubuntu:24.04 sleep infinity
docker ps # 一直在第一个容器
Bash
docker run ubuntu:24.04 /bin/echo "Hello world"Text
Unable to find image 'ubuntu:24.04' locally
24.04: Pulling from library/ubuntu
Hello world这条命令的完整语义是:用 ubuntu:24.04 镜像创建一个容器,在里面执行 /bin/echo "Hello world",命令结束容器即退出。
交互式容器
Bash
docker run -it ubuntu:24.04 /bin/bash
# 现在你在容器里的 shell,exit 退出-i保持标准输入打开-t分配一个伪终端(有提示符、支持颜色)- 两个一起用才像本地终端:
-it
后台运行
Bash
docker run -d --name web -p 8080:80 nginx
docker ps
docker logs -f web
docker exec -it web bash
docker stop web && docker rm web| 参数 | 含义 |
|---|---|
-d | 后台运行,打印容器 id |
--name | 起个名字,代替随机名 |
-p 8080:80 | 宿主 8080 映射到容器 80 |
-v host:container | 挂载目录或卷 |
-e KEY=VALUE | 设置环境变量 |
--rm | 退出后自动删除 |
--restart always | 崩溃与开机自动重启 |
容器为什么立刻退出了
容器的生命周期绑定主进程:主进程结束,容器就结束。docker run -d ubuntu 里没有前台进程,容器启动后立刻退出——这是新手最常踩的坑。要让容器常驻,主进程必须是前台运行的(如 nginx -g 'daemon off;'、tail -f /dev/null)。
Bash
docker run -d --name sleeper ubuntu:24.04 sleep infinity
docker ps # 一直在