使用 Docker Buildx 构建镜像并进入 Bash 的完整教程

使用 Docker Buildx 构建镜像并进入 Bash 的完整教程

在日常开发中,使用 Docker 构建多架构镜像或者想调试镜像时,可能需要进入镜像的 shell。本文将详细介绍如何使用 docker buildx build 构建镜像,并进入 bash。


1. 安装并启用 Buildx

如果你使用 Docker Desktop,通常已经自带 Buildx。 创建并使用一个 buildx builder:

1
2
docker buildx create --use
docker buildx inspect --bootstrap

2. 构建镜像

2.1 使用指定 Dockerfile 构建

假设你的 Dockerfile 名为 Dockerfile.prod

1
docker buildx build -f Dockerfile.prod -t myapp:latest .
  • -f Dockerfile.prod:指定 Dockerfile
  • -t myapp:latest:打标签
  • .:构建上下文目录

2.2 构建并支持多架构

1
docker buildx build   --platform linux/amd64,linux/arm64   -t myrepo/myapp:latest   --push   -f Dockerfile.prod   .
  • --platform:指定架构
  • --push:直接推送到 registry

注意:多架构镜像无法直接 --load 到本地,需要 --push


3. 构建后进入 Bash

3.1 构建并加载到本地

1
docker buildx build --load -t myapp:latest -f Dockerfile .
  • --load:加载到本地 Docker
  • 这样可以用 docker images 查看镜像

3.2 运行容器并进入 bash

1
docker run -it --rm myapp:latest /bin/bash
  • -it:交互式终端
  • --rm:退出后删除容器
  • /bin/bash:进入 bash,如果只有 sh,则改为 /bin/sh

3.3 一步到位

1
docker buildx build --load -t myapp:latest -f Dockerfile . && docker run -it --rm myapp:latest /bin/bash

这样构建完成后直接进入容器的 bash,非常方便调试。


4. 小结

  • docker buildx build 支持多架构和直接推送 registry
  • 使用 --load 可以将镜像加载到本地,方便调试
  • 进入 bash 可以快速调试镜像内部环境
Built with Hugo
Theme Stack designed by Jimmy