前言

项目打完镜像后发现镜像比想象中大多了

进容器一看发现整个项目都被拷过去了,明明配置了.dockerignore为什么没生效呢

项目结构如下:

$ tree -L 2
.
├── build_docker_image.sh
├── docker
│   ├── Dockerfile
│   ├── .dockerignore
│   └── docker_run_container.sh
├── main.py
...

解决

参考:https://docs.docker.com/build/concepts/context/#dockerignore-files

If you use multiple Dockerfiles, you can use different ignore-files for each Dockerfile. You do so using a special naming convention for the ignore-files. Place your ignore-file in the same directory as the Dockerfile, and prefix the ignore-file with the name of the Dockerfile, as shown in the following example.

就是如果不在项目根目录下,需要遵守特殊规则,需要给.dockerignore加上指定dockerfile名字的前缀。

.
├── index.ts
├── src/
├── docker
│   ├── build.Dockerfile
│   ├── build.Dockerfile.dockerignore
│   ├── lint.Dockerfile
│   ├── lint.Dockerfile.dockerignore
│   ├── test.Dockerfile
│   └── test.Dockerfile.dockerignore
├── package.json
└── package-lock.json

基于我的情况给.dockerignore加上前缀就行

$ tree -L 2
.
├── build_docker_image.sh
├── docker
│   ├── Dockerfile
│   ├── Dockerfile.dockerignore # .dockerignore -> Dockerfile.dockerignore即可
│   └── docker_run_container.sh
├── main.py
...