What happens to a file created in a Docker container after it is stopped?
sobes.tech AI
Answer from AI
A file created inside a Docker container will be saved on the container's filesystem layer. When the container is stopped, this layer is not deleted, so the data persists.
However, when the container is removed (docker rm), all layers, including the writable layer, are also deleted, and the file is lost.
To persist data created inside the container for a long time and independently of its lifecycle, the following are used:
-
Volumes: The recommended method. Docker manages the lifecycle of volumes. Data is stored outside the container, often in a special directory on the host system, isolated from the container's filesystem.
// Create a volume docker volume create mydata // Run a container with the volume mounted docker run -d --name mycontainer -v mydata:/app/data myimage -
Bind Mounts: They attach a directory on the host system to a directory inside the container. This is useful for development when direct access to host files (e.g., source code) is needed. Docker manages the files on the host only indirectly.
// Run a container with a bind mount docker run -d --name mycontainer -v /path/on/host:/app/data myimage
Thus, if a file is created without using volumes or bind mounts, it will disappear after the container is removed but not after it is stopped. When using volumes or bind mounts, data is preserved regardless of the container's state or existence.