# How to preserve data when the docker container exits?

When a Docker container exits, any data that was not persisted to a persistent storage will be lost. To preserve data when a Docker container exits, you can use one or more of the following methods:

## Use Docker volumes

Docker volumes are a way to persist data outside of the container file system. You can create a volume using the `docker volume create` command, and then mount the volume inside the container using the `v` option when running the container. This will allow any data written to the mounted volume to be preserved even when the container is removed or recreated.

For example, you can create a new volume named **`mydata`** using the following command:

```bash
docker volume create mydata
```

You can then run a container and mount the **`mydata`** volume inside the container using the following command:

```bash
docker run -it -v mydata:/app/data my-image
```

This will mount the **`mydata`** volume at the **`/app/data`** directory inside the container, allowing any data written to that directory to be preserved when the container is removed or recreated.

## Use bind mounts

Bind mounts are a way to mount a directory or file from the host file system inside the container. This allows data to be shared between the container and the host, and any data written to the mounted directory or file will be preserved even when the container is removed or recreated.For example, you can run a container and mount the **`/path/to/data`** directory on the host at the **`/app/data`** directory inside the container using the following command:

```bash
docker run -it -v /path/to/data:/app/data my-image
```

This will allow any data written to the **`/path/to/data`** directory on the host to be preserved even when the container is removed or recreated.

## Use a Dockerfile to persist data

If you're building your own Docker image, you can use a Dockerfile to copy any required data into the image itself. This will allow the data to be persisted even when the container is removed or recreated.

For example, you can add the following line to your Dockerfile to copy a file named **`data.txt`**  into the image:

```bash
COPY data.txt /app/data.txt
```

This will copy the **`data.txt`** file into the **`/app/data.txt`** directory inside the image, allowing the data to be persisted even when the container is removed or recreated. 

By using one or more of these methods, you can ensure that any data required by your Docker container is persisted and preserved even when the container exits.

[ad-logs]