如何在CentOS或Fedora上运行Docker容器?
原创怎样在CentOS或Fedora上运行Docker容器?
Docker 是一个开源的应用容器引擎,它允许开发者打包他们的应用以及应用的依靠包到一个可移植的容器中,然后发布到任何流行的 Linux 机器上,也可以实现虚拟化。Docker 容器是完全使用沙箱机制,二者之间之间不会有任何接口(类似 iPhone 的 app)。由此利用 Docker 可以进行一次编写,到处运行。
安装Docker
在 CentOS 或 Fedora 上安装 Docker 非常明了,以下是在这些操作系统上安装 Docker 的步骤:
1. 安装Docker引擎
以下是在 CentOS 7 或 Fedora 28 上安装 Docker 的命令:
sudo yum install -y yum-utils
sudo yum-config-manager --add-repo https://download.docker.com/linux/centos/docker-ce.repo
sudo yum install -y docker-ce docker-ce-cli containerd.io
对于 CentOS 8 或 Fedora 29 及更高版本,命令如下:
sudo dnf -y install dnf-plugins-core
sudo dnf config-manager --add-repo https://download.docker.com/linux/centos/docker-ce.repo
sudo dnf install -y docker-ce docker-ce-cli containerd.io
安装完成后,可以使用以下命令启动 Docker 服务:
sudo systemctl start docker
然后,确保 Docker 服务在启动时自动运行:
sudo systemctl enable docker
2. 验证Docker安装
要验证 Docker 是否已正确安装,可以使用以下命令运行一个明了的 Hello World 容器:
sudo 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.
3. The Docker daemon created a new container from that image which runs as a command line interface.
4. Finally, the container executed the "echo" command to output the "Hello from Docker!" message.
To try a different image, run: docker run [REGISTRY_HOST]/[IMAGE_NAME]:[TAG]
运行Docker容器
在安装 Docker 后,您可以开端运行容器。以下是一些基本的命令来运行 Docker 容器:
1. 运行一个明了的容器
以下是一个明了的命令,用于运行一个名为 nginx 的容器,该容器将从 Docker Hub 下载并运行官方的 nginx 容器镜像:
sudo docker run -d -p 8080:80 nginx
这个命令做了以下几件事情:
- 使用 `-d` 参数在后台运行容器。
- 使用 `-p 8080:80` 将容器的 80 端口映射到宿主机的 8080 端口。
- 运行官方的 nginx 容器镜像。
您现在可以在浏览器中访问 http://localhost:8080 来查看 nginx 的默认网页。
2. 运行带有持久存储的容器
以下是一个示例,展示了怎样使用 Docker 卷来持久化数据:
sudo docker run -d -p 8080:80 --name mynginx -v /my/custom/nginx.conf:/etc/nginx/nginx.conf nginx
在这个命令中,`-v` 参数用于将宿主机上的 `/my/custom/nginx.conf` 文件挂载到容器内的 `/etc/nginx/nginx.conf` 文件。这意味着容器内的 nginx 配置将使用宿主机上的配置文件。
3. 运行带有环境变量的容器
您可以通过使用 `-e` 参数为容器设置环境变量:
sudo docker run -d -p 8080:80 --name mynginx -e NGINX_HOST=localhost nginx
在这个命令中,`NGINX_HOST` 环境变量被设置为 `localhost`。
管理Docker容器
以下是一些基本的 Docker 容器管理命令:
1. 列出所有容器
sudo docker ps