Hello World 与第一个容器
约 695 字大约 2 分钟
布欧-Lewyon
2026-05-15
首页 › Docker › 快速入门(在新窗口打开) › Hello World 与第一个容器
运行 Hello World
docker run hello-world输出:
Hello from Docker!
This message shows that your installation appears to be working correctly.
To generate this message, Docker took the following steps:
1. The Docker client contacted the Docker daemon.
2. The Docker daemon pulled the "hello-world" image from the Docker Hub.
(amd64)
3. The Docker daemon created a new container from that image which runs the
executable that produces the output you are reading.
4. The Docker daemon streamed that output to the Docker client, which sent it
to your terminal.整个过程分析:
运行 Nginx Web 服务器
# 下载运行 Nginx,映射端口 8080
docker run -d -p 8080:80 --name my-nginx nginx:alpine参数说明:
| 参数 | 含义 |
|---|---|
-d | 后台运行(detached) |
-p 8080:80 | 宿主机 8080 端口映射到容器 80 端口 |
--name my-nginx | 给容器命名 |
nginx:alpine | 镜像名称(Nginx 的 Alpine 精简版) |
# 验证:访问 http://localhost:8080
curl http://localhost:8080
# 查看运行中的容器
docker ps查看容器日志
# 查看 Nginx 访问日志
docker logs my-nginx
# 实时追踪
docker logs -f my-nginx停止与删除容器
# 停止容器
docker stop my-nginx
# 删除容器(需要先停止)
docker rm my-nginx
# 一行完成:强制删除运行中的容器
docker rm -f my-nginx容器生命周期
交互式容器
# 运行 Ubuntu 容器,进入交互式 Shell
docker run -it --name my-ubuntu ubuntu:22.04 bash
# 在容器中执行命令(已在容器内)
apt update
apt install curl -y
curl --version
exit # 退出容器,容器停止
# 退出后重启并再次进入
docker start my-ubuntu
docker exec -it my-ubuntu bash| 参数 | 含义 |
|---|---|
-i | 交互模式(保持 STDIN 打开) |
-t | 分配伪终端(TTY) |
bash | 容器启动后执行的命令 |
--rm 自动清理
# 容器退出后自动删除
docker run --rm -it ubuntu:22.04 bash适合一次性任务(测试/调试),避免残留容器堆积。
小结
docker run从镜像创建并启动容器;本地无镜像时自动拉取。-d后台运行,-it交互运行,-p端口映射,--name命名。docker ps查看运行中容器,docker stop停止,docker rm删除,-f强制删除。docker logs查看输出,-exec -it进入已运行的容器。--rm让容器退出时自动清理,适合一次性任务。
