4

Docker images create with multiple layers, I want to convert this to single layer is there any docker build command to achive this ? i googled for but cant find anything

  • This is not intended by docker. But you can reduce the number of your layers in combining multiple commands with e.g. the `RUN` command. For example, you can combine `RUN echo foo` and `RUN echo bar` into a single command (and therefore a single command): `RUN echo foo && echo bar` – n2o Sep 26 '16 at 07:49

5 Answers5

5

I have just workaround by using multistage build (the last build will be just a COPY from the previous build)

FROM alpine as build1
RUN echo "The 1st Build"

FROM scratch
COPY --from=build1 / /
Mouaad
  • 106
  • 1
  • 4
4

No command to achieve that, and a single layer image is against docker's design concept. This Understand images, containers, and storage drivers doc described why docker image has multiple layers. In short, image layers are one of the reasons Docker is so lightweight. When you change a Docker image, such as when you update an application to a new version, a new layer is built and replaces only the layer it updates. Besides, even your image has only one layer, when you create a container with that image, docker still will add a thin Read/Writable container layer on the top of your image layer.

If you just want to move your image around and think one single layer could make it easier, you probably should try to use docker save command to create a tar file of it.

Or you have more complicated requirements, you may need to use VM image rather than docker image.

Haoming Zhang
  • 2,672
  • 2
  • 28
  • 32
2

First option:

# docker image build .
# docker run <your-image>
# docker container export <container-id created from previous command> -o myimage.tar.gz
# docker image import myimage.tar.gz

The imported image will be a single layer file system image.

Second option: (not a complete solution) - use multi stage builds to reduce number of image layers.

Vijayendar Gururaja
  • 752
  • 1
  • 9
  • 16
2

During build we can also pass --squash option to make it a single layer image.

Experimental (daemon)API 1.25+

Squash newly built layers into a single new layer https://docs.docker.com/engine/reference/commandline/image_build/

solvease
  • 529
  • 2
  • 11
  • This will be most helpful, but (unfortunately) still labelled experimental in Dec 2021. – Jeff W Dec 02 '21 at 13:28
  • Sure, but you can enable experimental features in Docker. My team have used squash for about 3 years now and we haven't had any issues. You can enable experimental by following this post: https://stackoverflow.com/questions/44346322/how-to-run-docker-with-experimental-functions-on-ubuntu-16-04 – Mihnea Cristian Marin Dec 24 '21 at 09:14
0

Flattening a Docker Image to a Single Layer:

docker run -d --name flat_container nginx
docker export flat_container > flat.tar
cat flat.tar | docker import - flat:latest
docker image history flat
ragumix
  • 1
  • 2