Docker-compose命令-build

命令

docker-compose build

描述

Build or rebuild services
构建或重建服务

用法

1
build [options] [--build-arg key=val...] [SERVICE...]

选项

1
2
3
4
5
6
7
8
9
10
11
Options:
--build-arg key=val Set build-time variables for services.
--compress Compress the build context using gzip.
--force-rm Always remove intermediate containers.
-m, --memory MEM Set memory limit for the build container.
--no-cache Do not use cache when building the image.
--no-rm Do not remove intermediate containers after a successful build.
--parallel 并行构建镜像
--progress string Set type of progress output (`auto`, `plain`, `tty`).
--pull Always attempt to pull a newer version of the image.
-q, --quiet Don't print anything to `STDOUT`.

注意

如果更改了Dockerfile文件,则可以重复执行build命令重新构建,注意需要同时更改compose文件中的image镜像版本

示例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
# 目录结构
$ tree
├── data
│ └── demo.txt
├── docker-compose.yml
└── Dockerfile
$ cat Dockerfile
FROM alpine:3.13
RUN sed -i 's/dl-cdn.alpinelinux.org/mirrors.aliyun.com/g' /etc/apk/repositories
CMD ["/bin/bash"]
$ cat docker-compose.yml
version: "3.8"
services:
demo:
build: .
image: demo:1.1.0
restart: always
volumes:
- ./data:/data
- demo-logs:/logs
volumes:
demo-logs:
# 构建服务镜像
$ docker-compose build
Building demo
Sending build context to Docker daemon 4.608kB
Step 1/3 : FROM alpine:3.13
---> 6b7b3256dabe
Step 2/3 : RUN sed -i 's/dl-cdn.alpinelinux.org/mirrors.aliyun.com/g' /etc/apk/repositories
---> Running in 90cfa4272c52
Removing intermediate container 90cfa4272c52
---> 7ce488d2353a
Step 3/3 : CMD ["/bin/bash"]
---> Running in 1695c25617d8
Removing intermediate container 1695c25617d8
---> 93e22893911b
Successfully built 93e22893911b
Successfully tagged demo:1.1.0
$ docker images
REPOSITORY TAG IMAGE ID CREATED SIZE
demo 1.1.0 bcfaf9c55c9b 3 seconds ago 5.62MB
alpine 3.13 6b7b3256dabe 4 months ago 5.62MB
# 验证镜像
$ docker run --rm demo:1.1.0 cat /etc/apk/repositories
https://mirrors.aliyun.com/alpine/v3.13/main
https://mirrors.aliyun.com/alpine/v3.13/community
# 更改Dockerfile文件,更改CMD为/bin/sh
$ cat Dockerfile
FROM alpine:3.13
RUN sed -i 's/dl-cdn.alpinelinux.org/mirrors.aliyun.com/g' /etc/apk/repositories
CMD ["/bin/sh"]
# 更改compose文件,更改image版本为1.1.1
$ grep image docker-compose.yml
image: demo:1.1.1
# 重新构建镜像
$ docker-compose build
Step 3/3 : CMD ["/bin/sh"]
...
$ docker images
REPOSITORY TAG IMAGE ID CREATED SIZE
demo 1.1.1 188c2693ff90 4 seconds ago 5.62MB
demo 1.1.0 bcfaf9c55c9b About a minute ago 5.62MB

# 指定目录路径./app,注意默认为相对路径,和docker-compose.yml文件同级的目录
version: "3.8"
services:
demo:
build: app
image: demo:1.2.0
# 指定目录下的Dockerfile文件,context也支持指定url或git仓库地址
version: "3.8"
services:
demo:
build:
context: app
dockerfile: Dockerfile-dev
image: demo:1.2.1