synchronization
This commit is contained in:
99
Docker/Docs/Docker构建镜像.md
Normal file
99
Docker/Docs/Docker构建镜像.md
Normal file
@@ -0,0 +1,99 @@
|
||||
> 本文作者:丁辉
|
||||
|
||||
# Docker 构建镜像
|
||||
|
||||
> Docker 构建镜像有很多门道,今天咱就来说道说道,直接实际演示
|
||||
>
|
||||
> 为了方便简单演示,咱们就随便打包一份文件当作示例好了
|
||||
|
||||
## 多阶段构建
|
||||
|
||||
- 编写 Dockerfile
|
||||
|
||||
> 使用 AS 参数,后面定义名称
|
||||
>
|
||||
> 第二个容器直接 COPY 第一个容器所构建好的文件包使用
|
||||
|
||||
```bash
|
||||
vi Dockerfile
|
||||
```
|
||||
|
||||
```dockerfile
|
||||
FROM alpine AS builder
|
||||
|
||||
RUN apk add git \
|
||||
&& git clone https://gitee.com/offends/Docs.git \
|
||||
&& tar -cvf Docker-Template.tar ./Docker-Template
|
||||
|
||||
FROM alpine
|
||||
|
||||
COPY --from=builder /Docker-Template.tar /
|
||||
```
|
||||
|
||||
开始构建
|
||||
|
||||
```bash
|
||||
docker build -t app:v1 .
|
||||
```
|
||||
|
||||
## 多阶段构建,选定构建容器
|
||||
|
||||
- 编写 Dockerfile
|
||||
|
||||
> 当我们在一个 Dockerfile 中定义了多个容器构建,这里我门可以使用 `--target` 参数指定特定的容器构建
|
||||
>
|
||||
|
||||
```bash
|
||||
vi Dockerfile
|
||||
```
|
||||
|
||||
```dockerfile
|
||||
FROM alpine AS builder
|
||||
|
||||
RUN apk add git \
|
||||
&& git clone https://gitee.com/offends/Docs.git \
|
||||
&& tar -cvf Docker-Template.tar ./Docker-Template
|
||||
|
||||
FROM alpine AS builder-2
|
||||
|
||||
COPY --from=builder /Docker-Template.tar /
|
||||
RUN rm -rf /Docker-Template.tar
|
||||
|
||||
FROM alpine AS builder-3
|
||||
|
||||
COPY --from=builder /Docker-Template.tar /
|
||||
RUN tar -xvf /Docker-Template.tar
|
||||
```
|
||||
|
||||
开始构建
|
||||
|
||||
```bash
|
||||
docker build --target builder-3 -t app:v1 .
|
||||
```
|
||||
|
||||
## 替换构建镜像或参数
|
||||
|
||||
- 编写 Dockerfile
|
||||
|
||||
> Dockerfile 可定义变量在外部指定
|
||||
>
|
||||
|
||||
```bash
|
||||
vi Dockerfile
|
||||
```
|
||||
|
||||
```dockerfile
|
||||
# 默认镜像使用 alpine ,通过外部定义修改镜像为 ubuntu
|
||||
ARG IMAGE=alpine
|
||||
FROM ${IMAGE}
|
||||
|
||||
# 定义一个ENV,默认值为: default_env,外部传入 NAME_ARG 让 NAME 变量值改变为 demo_env
|
||||
ARG NAME_ARG
|
||||
ENV NAME=${NAME_ARG:-default_env}
|
||||
```
|
||||
|
||||
开始构建
|
||||
|
||||
```bash
|
||||
docker build --build-arg NAME_ARG=demo_env --build-arg IMAGE=ubuntu -t app:v1 .
|
||||
```
|
Reference in New Issue
Block a user