Docker Hello World

跑通第一个容器,理解 run 的常用参数与容器生命周期。

Beginner
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 world

Full 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
FlagMeaning
-dDetached — run in background, print the container id
--nameGive it a name instead of a random one
-p 8080:80Map host port 8080 to container port 80
-v host:containerMount a directory or volume
-e KEY=VALUESet an environment variable
--rmDelete the container when it exits
--restart alwaysRestart 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          # 一直在

Friends & Partners