使用 Dockerfile 构建 Docker 镜像

DockerBeginner
立即练习

介绍

欢迎来到未来的太空港,这里是星际旅行的繁忙枢纽。作为一名星际通讯官,你的任务是确保所有航天器在准备进行宇宙航行时,都配备了必要的软件和配置。在本实验中,你将学习如何使用 Docker 从 Dockerfiles 构建自定义镜像,确保航天器配备了星际旅程所需的软件软件包和配置。

这是一个实验(Guided Lab),提供逐步指导来帮助你学习和实践。请仔细按照说明完成每个步骤,获得实际操作经验。根据历史数据,这是一个 初级 级别的实验,完成率为 100%。获得了学习者 96% 的好评率。

创建 Dockerfile

在此步骤中,你将创建一个 Dockerfile 来定义航天器软件系统的环境。

  1. ~/project 目录中创建一个名为 Dockerfile 的新文件。
  2. 将以下内容添加到 Dockerfile
## Use an official Python runtime as the base image
FROM python:3.9-slim

## Set the working directory
WORKDIR /app

## Copy the current directory contents into the container at /app
COPY . /app

## Install any needed packages specified in requirements.txt
RUN pip install --no-cache-dir -r requirements.txt

## Make port 80 available to the world outside this container
EXPOSE 80

## Define environment variable
ENV NAME World

## Run app.py when the container launches
CMD ["python", "app.py"]
  1. ~/project 目录中创建一个 requirements.txt 文件。添加航天器软件所需的 Python 包。

构建 Docker 镜像

在此步骤中,你将使用 Dockerfile 为航天器的软件系统构建自定义 Docker 镜像。

  1. 打开终端并导航到 ~/project 目录。
  2. 运行以下命令构建 Docker 镜像:
docker build -t spaceship-software .
  1. 验证 Docker 镜像是否已成功构建并标记为 spaceship-software

总结

在此次实验中,你学习了如何创建 Dockerfile 来定义航天器软件系统的环境,以及如何基于 Dockerfile 构建自定义 Docker 镜像。通过遵循这些步骤,你掌握了使用 Docker 为太空任务准备软件配置的基本技能。