启动容器前构建镜像
在前面的步骤中,我们使用了 Docker Hub 上预构建的镜像(如 nginx:latest
)。但实际开发中,你经常需要为应用程序构建自定义的 Docker 镜像。
Docker Compose 可以在启动服务前自动构建 docker-compose.yml
文件中定义的镜像。这通常通过为服务指定 build
上下文而非 image
名称来实现。
让我们修改 docker-compose.yml
文件来构建一个简单的自定义 Nginx 镜像。
首先,在 ~/project
目录下创建名为 nginx_custom
的新目录:
cd ~/project
mkdir nginx_custom
接着,在 nginx_custom
目录中创建 Dockerfile
:
nano ~/project/nginx_custom/Dockerfile
将以下内容添加到 Dockerfile
:
FROM nginx:latest
RUN echo '<h1>Hello from Custom Nginx!</h1>' > /usr/share/nginx/html/index.html
这个 Dockerfile
基于官方的 nginx:latest
镜像,然后将默认的 index.html
文件替换为自定义内容。
接下来,修改 ~/project/docker-compose.yml
文件,让 web
服务使用这个 Dockerfile
构建镜像。打开文件进行编辑:
nano ~/project/docker-compose.yml
将 web
服务的定义从 image
改为 build
:
version: "3.8"
services:
web:
build: ./nginx_custom
ports:
- "80:80"
现在当你运行 docker compose up
时,Docker Compose 会先构建 ./nginx_custom
目录中 Dockerfile
定义的镜像,然后使用新构建的镜像启动容器。
确保当前位于 ~/project
目录并运行:
cd ~/project
docker compose up -d
你将看到输出显示 Docker Compose 正在构建镜像,然后创建并启动容器。
使用 curl
验证是否成功提供了自定义 Nginx 页面:
curl http://localhost
你应该会看到输出 <h1>Hello from Custom Nginx!</h1>
,这确认了镜像已成功构建且容器正在运行自定义内容。
清理时停止运行中的服务:
cd ~/project
docker compose down