Docker 安装 Linux
本章将介绍如何使用 Docker 运行常见的 Linux 发行版容器,包括 Ubuntu、Alpine 和 CentOS。
Ubuntu 容器
拉取和运行
bash
# 拉取最新版 Ubuntu
docker pull ubuntu:24.04
# 交互式运行
docker run -it --name my-ubuntu ubuntu:24.04 /bin/bash
# 后台运行
docker run -d --name ubuntu-server ubuntu:24.04 tail -f /dev/null常用操作
bash
# 进入容器
docker exec -it my-ubuntu /bin/bash
# 在容器内更新包管理器
apt-get update && apt-get upgrade -y
# 安装常用工具
apt-get install -y curl wget vim net-tools创建自定义 Ubuntu 镜像
dockerfile
FROM ubuntu:24.04
RUN apt-get update && \
apt-get install -y curl wget vim git net-tools && \
apt-get clean && \
rm -rf /var/lib/apt/lists/*
CMD ["/bin/bash"]bash
docker build -t my-ubuntu:custom .Alpine 容器
Alpine Linux 是一个极其轻量的 Linux 发行版,非常适合作为 Docker 基础镜像。
拉取和运行
bash
# Alpine 镜像仅约 5MB
docker pull alpine:3.19
# 交互式运行
docker run -it --name my-alpine alpine:3.19 /bin/sh包管理
Alpine 使用 apk 包管理器:
bash
# 更新包索引
apk update
# 安装软件
apk add curl wget vim git
# 搜索包
apk search nginx
# 删除包
apk del curl自定义 Alpine 镜像
dockerfile
FROM alpine:3.19
RUN apk update && \
apk add --no-cache curl wget bash && \
rm -rf /var/cache/apk/*
CMD ["/bin/bash"]Alpine vs Ubuntu 镜像大小对比
| 镜像 | 大小 |
|---|---|
| alpine:3.19 | ~5 MB |
| ubuntu:24.04 | ~78 MB |
| debian:12 | ~116 MB |
CentOS 容器
⚠️ CentOS 8 已于 2021 年底停止维护,建议使用 CentOS Stream 或 Rocky Linux / AlmaLinux 作为替代。
拉取和运行
bash
# CentOS Stream 9
docker pull quay.io/centos/centos:stream9
# 交互式运行
docker run -it --name my-centos quay.io/centos/centos:stream9 /bin/bash
# 或使用 Rocky Linux(CentOS 替代品)
docker pull rockylinux:9
docker run -it --name my-rocky rockylinux:9 /bin/bash包管理
bash
# 更新系统
dnf update -y
# 安装软件
dnf install -y curl wget vim git net-tools
# 搜索包
dnf search nginx自定义 CentOS 镜像
dockerfile
FROM quay.io/centos/centos:stream9
RUN dnf update -y && \
dnf install -y curl wget vim git && \
dnf clean all
CMD ["/bin/bash"]实用场景
场景一:测试不同 Linux 环境
bash
# 快速切换不同 Linux 环境进行测试
docker run -it --rm ubuntu:24.04 bash -c "cat /etc/os-release"
docker run -it --rm alpine:3.19 sh -c "cat /etc/os-release"
docker run -it --rm rockylinux:9 bash -c "cat /etc/os-release"场景二:搭建开发环境
bash
# 创建一个包含开发工具的容器
docker run -it \
--name dev-env \
-v $(pwd):/workspace \
-w /workspace \
ubuntu:24.04 /bin/bash场景三:运行特定版本的系统服务
bash
# 在 Ubuntu 容器中运行 SSH 服务
docker run -d \
--name ssh-server \
-p 2222:22 \
ubuntu:24.04 \
bash -c "apt-get update && apt-get install -y openssh-server && mkdir /run/sshd && /usr/sbin/sshd -D"本章小结
使用 Docker 运行 Linux 发行版容器非常简单,可以快速搭建各种 Linux 环境用于开发、测试和学习。Alpine 因其极小的体积,是构建生产镜像的首选基础镜像。