Docker creating multiple images

RmR*_*RmR 6 docker dockerfile docker-compose

I am new to Docker and find that there are numerous images that are getting created (as seen in sudo docker images) and found somewhere in stackoverflow to periodically run sudo docker rmi $(sudo docker images -q) to remove all images. Why so many images get created? is there something wrong in my configuration?

docker-compose.yml

nginx:
  build: ./nginx
  restart: always
  ports:
    - "80:80"
    - "443:443"
  volumes:
    - /etc/letsencrypt/:/etc/letsencrypt/
  links:
    - node:node

node:
  build: ./node
  restart: always
  ports:
   - "8080:8080"
  volumes:
    - ./node:/usr/src/app
    - /usr/src/app/node_modules
Run Code Online (Sandbox Code Playgroud)

The nginx dockerfile is

FROM nginx:alpine

COPY nginx.conf /etc/nginx/conf.d/default.conf
Run Code Online (Sandbox Code Playgroud)

The nodejs dockerfile is

FROM node:9.3.0-alpine

WORKDIR /usr/src/app

COPY package*.json /usr/src/app/

RUN npm install --only=production

COPY . /usr/src/app

EXPOSE 8080
CMD [ "npm", "start" ]
Run Code Online (Sandbox Code Playgroud)

The website/app works fine. Except that periodically, I am removing all containers, images and then run: sudo docker-compose up --build -d.

BMi*_*tch 7

图像是不可变的,因此您所做的任何更改都会导致创建新图像。由于您的 compose 文件指定了构建命令,因此当您启动容器时它将重新运行构建命令。如果您包含的任何文件发生COPY变化ADD,则不再使用现有的图像缓存,它将构建新图像而不删除旧图像。

请注意,我建议在撰写文件中命名您的图像,以便清楚正在重建哪个图像。您可以观察第一步的 compose 构建输出,该步骤不使用缓存报告,以了解发生了什么变化。如果我猜的话,破坏缓存并生成新图像的行是 Nodejs 中的这一行:

COPY . /usr/src/app
Run Code Online (Sandbox Code Playgroud)

如果您的容器中不需要正在更改并导致重建的文件,则使用文件.dockerignore来排除不需要的文件。


小智 5

我在构建 Dockerfile 时遇到了同样的问题。

我找到了解决方案,使用此命令来构建您的文件:

`docker build --rm -t <tag> .`
Run Code Online (Sandbox Code Playgroud)

该选项--rm会在成功构建后删除中间容器。