I'm basing this off the documentation I've read, I haven't tried it myself.
I'm basing this off the documentation I've read, I haven't tried it myself.
Some people have considered another approach: flattening an existing stack of images. Scripts for that are linked from the Docker issue on GitHub. I wasn't able to get any of these working, and the logic behind these seemed quite convoluted.
Still, my script is just a proof of concept - I tried whether it is possible to take the approach I use internally for Docker build scripts, and use it to build Dockerfiles. It seems it's possible, and it delivers good results. Time and actual usage will show whether it's a good idea; if this approach makes sense, it will hopefully make its way to the Docker core, and my hack won't stay relevant for too long.
EDIT: from the [github issue](https://github.com/dotcloud/docker/issues/332#issuecomment-2...):
"Currently the only way to "squash" the image is to create a container from it, export that container into a raw tarball, and re-import that as an image. Unfortunately that will cause all image metadata to be lost, including its history but also ports, env, default command, maintainer info etc. So it's really not great."
Which makes sense to me, because you have no idea if an arbitrary shell command is deterministic or not.
So a good way to optimize your Dockerfile is to put commands in an order like:
* dependencies, e.g. apt-get, useradd...
* containers configs PORT, ENV, USER from less likely to change to more likely to change
* ADD commands
* final RUN commands to setup your image