0

Docker novice here. Is Docker analogous to GitHub in that you can commit changes to an image without having to re-build the image from scratch? If yes, what commands are used to do that?

Right now every time I make a change to my code I delete the current Docker image using docker system prune -a and re-build the image using docker build -t appname.

David
  • 19
  • 2
  • IMHO live-editing a container and committing it is distinctly not a best practice: the Dockerfile/`docker build` system is pretty efficient and you always have a record in the filesystem or source control of what exactly went into your image, and when you need to rebuild it in six months with security updates there's no guesswork. Still, the list of commands in `docker help` might suggest something like what you're asking about. – David Maze Jul 20 '18 at 15:11

1 Answers1

3

There's no need to delete the existing image first, you can rebuild and create a tag to the same image name that already exists. Images themselves are resolved to an immutable image ID that does not change. To change the contents of an image, you must build a new image that has a new image ID. And then to use it, you need to start new containers referencing that new image.

A rebuild from scratch will reuse the cache, so only commands in your Dockerfile that changed, or are after a change, will result in a rebuild. The layers in the beginning of your Dockerfile that are same as previous builds will be reused between images. Those layers need to be built previous on this host (or there's a --cache-from option if you are building in ephemeral cloud environments). Order matters with the build cache, as does the exact hash of the files and their metadata that you copy into your image.

The docker image prune command is useful after you rebuild an image with the same image name. In that scenario, docker will delete old image ID's that no longer have a reference (image name) pointing to it, and do not currently have a container using it. Note that this also removes those old images from the build cache, so you may want to keep some old images around to speed up builds should a change get reverted from a commit.

BMitch
  • 231,797
  • 42
  • 475
  • 450