Docker实践:修复Dockerfile与多阶段构建

1、有一个存在语法错误的简单 Dockerfile,内容为:FROM ubuntu:latest LABEL author=”sathyabhat” LABEL description=”An example Dockerfile” RUN apt-get install python COPY hello-world.py CMD python hello-world.py。请修复该 Dockerfile 并添加一些常用指令。同时,创建一个 hello-world.py 文件,该文件读取环境变量 NAME 并打印 Hello, $NAME!。如果环境变量未定义,则打印 “Hello, World!”。然后构建 Dockerfile 并运行 Docker 镜像,并尝试在运行时覆盖环境变量。

1. 创建 hello-world.py 文件

#!/usr/bin/env python3

from os import getenv

if getenv('NAME') is None:
    name = 'World'
else:
    name = getenv('NAME')
print(f"Hello, {name}!)")

2. 修复 Dockerfile

原始的 Dockerfile 存在语法错误, COPY 指令需要至少两个参数,我们需要指定目标路径。修复后的 Dockerfile 如下:

FROM ubuntu:latest

LABEL author="sathyabhat"
LABEL description="An example Dockerfile"

RUN apt-get update && apt-get install -y python3

COPY hello-world.py /app/

ENV NAME=World

CMD python3 /app/hello-world.py

3. 构建 Dockerfile

在包含 Dockerfile hello-world.py 的目录下运行以下命令构建 Docker 镜像:

docker build -t sathyabhat/chap04-ex1 .

4. 运行 Docker 镜像

docker run sathyabhat/chap04-ex1

5. 在运行时覆盖环境变量

docker run -e NAME=Readers sathyabhat/chap04-ex1

2、在本次练习中,你将构建一个附加了 Docker 卷的 Nginx Docker 镜像,该卷包含

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值