Persisting Data with Containers
Introduction: Why Data Persistence Matters
Welcome back! In the last lesson, you learned how to build your own Docker image for a simple web application, run it as a container, and access it from your browser. You also saw how easy it is to start, stop, and remove containers. However, there is an important detail about containers that you need to understand as you move forward: containers are ephemeral. This means that any files created or changed inside a container will disappear as soon as the container is removed.
Imagine you are running a web app that writes logs, stores user uploads, or saves configuration files. If you remove the container, all that data is lost. In real-world applications, you almost always need to keep some data between runs. For example, you might want to keep server logs for debugging, or you might need to store user-generated content. This is where data persistence comes in. In this lesson, you will learn how to make sure important files created by your app are saved on your computer, even after the container is gone.
Bind Mounts 101: Options and What We'll Use
Docker provides a few ways to persist data. The two most common are bind mounts and named volumes. A bind mount lets you map a specific directory or file from your host machine (your computer) into the container. This means anything the container writes to that directory will actually be saved on your host, and you can access it even after the container is removed. A named volume is managed by Docker and is stored in a special location on your system. Both methods are useful, but for this lesson, you will use a bind mount. This approach is simple and makes it easy to see the files your app creates right in your project folder.
You will mount a logs directory from your host into the container. This way, when your app writes log files, they will be saved on your computer and will not disappear when the container is removed.
App Update: Write Logs to a File
To see data persistence in action, you will update your web app so that it writes a log entry every time someone visits the home page. The app will create a logs directory (if it does not already exist) and append a line to logs/access.log with the current date and time.
Here is the updated app.py:
This code checks if the logs directory exists and creates it if needed. Every time the root URL is accessed, it appends a line to logs/access.log with the current timestamp. The log file path is relative to the app's working directory, which keeps things simple and predictable.
You will also need a requirements.txt file to specify your dependencies with pinned versions:
