Docker 是一个开源的应用容器引擎,可以让你打包、发布和运行应用。使用 Docker,你可以确保你的应用可以在任何环境中(开发、测试、生产)以相同的方式运行。下面,我将为你详细讲解如何在电脑上安装 Docker,并展示如何使用它来部署一个简单应用。
第一节:准备工作
在开始之前,请确保你的电脑满足以下条件:
- 操作系统:Windows、macOS 或 Linux
- 处理器架构:64 位
- 网络连接:互联网连接用于下载 Docker
第二节:安装 Docker
Windows 安装
- 访问 Docker 官方网站 下载 Docker Desktop for Windows。
- 双击下载的文件,按照提示进行安装。
- 安装完成后,重启你的电脑。
macOS 安装
- 打开终端。
- 输入以下命令安装 Docker:
brew cask install docker - 安装完成后,你可以通过 dockershop.com 网站中的 Docker Desktop for macOS 应用来启动 Docker。
Linux 安装
以 Ubuntu 为例:
- 打开终端。
- 输入以下命令安装 Docker:
sudo apt-get update sudo apt-get install docker.io - 安装完成后,输入以下命令启动 Docker:
sudo systemctl start docker
第三节:验证安装
安装完成后,可以通过以下命令验证 Docker 是否安装成功:
docker --version
如果你看到了 Docker 的版本信息,说明 Docker 已成功安装在你的电脑上。
第四节:运行第一个容器
接下来,我们将使用 Docker 来运行一个简单的 Hello World 容器。
- 打开终端。
- 输入以下命令运行 Hello World 容器:
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 daemon forked a new container from an image with id sha256:<hash>.
2. Configured a temporary volume for the container.
3. Set the container in noninteractive mode.
4. Attached standard input (stdin) to the container.
5. Attached standard output (stdout) to the container.
6. Attached standard error (stderr) to the container.
7. Started the container.
8. Sent an empty signal to the container.
9. Received an exit status from the container.
这样,你就成功地运行了第一个 Docker 容器。
第五节:部署应用
现在,我们将学习如何使用 Docker 部署一个简单的 web 应用。
- 首先,创建一个名为
webapp的文件夹。 - 在
webapp文件夹中创建一个名为Dockerfile的文件,并输入以下内容:
FROM nginx:latest
COPY ./ /usr/share/nginx/html/
这个 Dockerfile 告诉 Docker 使用最新的 Nginx 镜像,并将当前目录中的内容复制到 Nginx 的 /usr/share/nginx/html/ 目录下。
- 运行以下命令构建镜像:
docker build -t webapp .
- 运行以下命令启动容器:
docker run -d -p 8080:80 webapp
这将创建一个后台运行的容器,并将容器的 80 端口映射到宿主机的 8080 端口。
- 打开浏览器,访问
http://localhost:8080,你应该会看到你的 web 应用的页面。
通过以上步骤,你已经学会了如何在电脑上安装 Docker 并使用它来部署应用。现在,你可以利用 Docker 来简化你的开发、测试和部署流程,让你的工作更加高效。
