Skip to content

运行一个容器

原文:https://docs.docker.com/guides/walkthroughs/run-a-container/

在这个演练中,您将学习构建镜像和运行自己容器的基本步骤。此演练使用一个 Node.js 示例应用程序,但不需要了解 Node.js。

在 Docker Desktop 中运行镜像

步骤 1: 获取示例应用程序

如果您有 git,可以克隆示例应用程序的仓库。否则,您可以下载示例应用程序。选择以下选项之一。

在终端使用以下命令克隆示例应用程序仓库。

bash
git clone https://github.com/docker/welcome-to-docker

步骤 2: 查看项目文件夹中的 Dockerfile

要在容器中运行您的代码,最基本的需要是一个 Dockerfile。Dockerfile 描述了容器中的内容。此示例已包含一个 Dockerfile。对于您自己的项目,您需要创建自己的 Dockerfile。您可以在代码或文本编辑器中打开 Dockerfile 并探索其内容。

修改 Dockerfile 增加镜像加速 --registry=https://registry.npmmirror.com

Dockerfile
# Start your image with a node base image
FROM node:18-alpine

# The /app directory should act as the main application directory
WORKDIR /app

# Copy the app package and package-lock.json file
COPY package*.json ./

# Copy local directories to the current local directory of our docker image (/app)
COPY ./src ./src
COPY ./public ./public

# Install node packages, install serve, build the app, and remove dependencies at the end
RUN npm install --registry=https://registry.npmmirror.com \
    && npm install --registry=https://registry.npmmirror.com -g serve \
    && npm run build \
    && rm -fr node_modules

EXPOSE 3000

# Start the app using serve command
CMD [ "serve", "-s", "build" ]

步骤 3: 构建您的第一个镜像

运行容器总是需要一个镜像。在终端,运行以下命令来构建镜像。将 /path/to/welcome-to-docker/ 替换为您的 welcome-to-docker 目录的路径。

bash
cd /path/to/welcome-to-docker/
bash
docker build -t welcome-to-docker .

在上面的命令中,-t 标志为您的镜像标记一个名称,此处为 welcome-to-docker。点号 . 让 Docker 知道在哪里可以找到 Dockerfile。

构建镜像可能需要一些时间。构建完毕后,您可以在 Docker Desktop 的 镜像 标签中查看您的镜像。

步骤 4: 运行您的容器

要将您的镜像作为容器运行:

  1. 在 Docker Desktop 中,转到 镜像 标签。

  2. 在您的镜像旁边,选择 运行

  3. 展开 可选设置

  4. 主机端口 中,指定 8089指定主机端口 8089

  5. 选择 运行

步骤 5: 查看前端

您可以使用 Docker Desktop 访问正在运行的容器。选择 Docker Desktop 中您的容器旁的链接,或访问 http://localhost:8089 来查看前端。

选择容器链接

总结

在这次演练中,您构建了自己的镜像并将其作为容器运行。除了构建和运行自己的镜像外,您还可以从 Docker Hub 运行镜像。