简单的新建并发布镜像。
前言
将常用的命令放在这儿,再附加一个例子。
# 根据上下文路径的Dockerfile新建镜像
docker build -t <REPOSITORY>:<TAG> <CONTEXT_PATH>
docker login
docker push <REPOSITORY>:<TAG>
附一个多阶段构建的例子
# First stage: complete build environment
FROM maven:3.5.0-jdk-8-alpine AS builder
# add pom.xml and source code
ADD ./pom.xml pom.xml
ADD ./src src/
# package jar
RUN mvn clean package
# Second stage: minimal runtime environment
From openjdk:8-jre-alpine
# copy jar from the first stage
COPY --from=builder target/test-1.0.jar test.jar
# run jar
CMD ["java", "-jar", "test.jar"]
详细样例可以参考官方的Dockerfile最佳实践
例子
- 下面我们要:
- 下载一个Ubuntu镜像,设定工作目录为/home,将本地的test文件夹内容拷贝至/home/test其中,并且更新镜像
- 发布新的镜像
- 需要注意的是:
- COPY 命令只能复制上下文路径下的内容
- COPY 命令拷贝文件夹下的内容,并不拷贝文件夹本身
- COPY命令中右侧的Container路径如果是相对路径,那么与WORKDIR协同
- 上下文路径中不要包含无关文件,否则会影响build的速度,因为开始build的时候整个路径中的内容会被传给docker daemon
- RUN命令要合理分层,特别是删除文件时,由于每次RUN都会生成新的image,在下一个image删除冗余文件并不会对上一个image造成影响,image大小不会因此而减小,这点要特别注意
- 下面我们开始实现
Dockerfile 如下:
FROM ubuntu
WORKDIR /home
COPY test test
shell命令如下:
# 生成新镜像
D:\Workspace\docker>docker build -t nicelee/ubuntu:build-test .
[+] Building 4.9s (8/8) FINISHED
=> [internal] load build definition from Dockerfile 0.8s
=> => transferring dockerfile: 80B 0.0s
=> [internal] load .dockerignore 1.1s
=> => transferring context: 2B 0.0s
=> [internal] load metadata for docker.io/library/ubuntu:latest 0.0s
=> [1/3] FROM docker.io/library/ubuntu 0.0s
=> [internal] load build context 0.5s
=> => transferring context: 152B 0.0s
=> CACHED [2/3] WORKDIR /home 0.0s
=> [3/3] COPY test test 1.1s
=> exporting to image 1.4s
=> => exporting layers 1.1s
=> => writing image sha256:4a01e6f358980846437ef16cd988177d6d200a86c9d95d6526cab600ab749151 0.1s
=> => naming to docker.io/nicelee/ubuntu:build-test 0.1s
Use 'docker scan' to run Snyk tests against images to find vulnerabilities and learn how to fix them
# 查看镜像内容是否正确
D:\Workspace\docker>docker run -it nicelee/ubuntu:build-test
root@d448e286cc40:/home# ls -l
total 4
drwxr-xr-x 2 root root 4096 Oct 10 14:33 test
root@d448e286cc40:/home# cd test
root@d448e286cc40:/home/test# ls -l
total 16
-rwxr-xr-x 1 root root 615 Oct 10 12:36 index.py
-rwxr-xr-x 1 root root 21 Oct 10 11:17 test.txt
root@d448e286cc40:/home/test# exit
# 发布新镜像
D:\Workspace\docker>docker push nicelee/ubuntu:build-test
The push refers to repository [docker.io/nicelee/ubuntu]
37cea314f82e: Pushed
5f70bf18a086: Pushed
da55b45d310b: Mounted from library/ubuntu
build-test: digest: sha256:ecb8f9fde6d65bc638571ec91f53a6be0b3ee4aeafd126118b8ff6d96504658c size: 942