# How to redirect Docker logs to file?

To redirect Docker container logs to a file, you can use the `--log-driver` and `--log-opt` options when running the container. Docker provides several logging drivers, and you can choose one that suits your needs. The most commonly used logging drivers are `json-file` (the default), `syslog`, and `journald`. Here's how you can redirect Docker logs to a file using the `json-file` logging driver:

## 1. **Create a Docker Container with Redirected Logs**

This will run the container with the `json-file` logging driver and redirect the container's logs to files. The logs will be stored in the `/var/lib/docker/containers/container_id/container_id-json.log` file on the host, where `container_id` is the unique ID of your container.

```bash
docker run -d --name your_container_name \
  --log-driver=json-file \
  --log-opt max-size=10m \
  --log-opt max-file=3 \
  your_image_name
```

Explanation:

- `d`: Run the container in detached mode (in the background).
- `-name your_container_name`: Give a name to the container.
- `-log-driver=json-file`: Use the `json-file` logging driver to redirect logs to files.
- `-log-opt max-size=10m`: Set the maximum size of each log file to 10 megabytes (adjust as needed).
- `-log-opt max-file=3`: Set the maximum number of log files to rotate before removing old logs (adjust as needed).
- `your_image_name`: Replace this with the name of the Docker image you want to run in the container.

## 2. **View the Logs**

To view the logs of the running container, you can use the `docker logs` command:

```bash
docker logs your_container_name
```

This will display the logs on the console.

If you want to save the logs to a file on your host system, you can use output redirection:

```bash
docker logs your_container_name > container_logs.txt
```

This will save the container logs to the **`container_logs.txt`** file on your host system.

Remember to adjust the logging driver and options according to your requirements. Other logging drivers, such as **`syslog`** or **`journald`**, are also available and might be more suitable for specific use cases. The **`json-file`** driver is commonly used for redirecting logs to files when you want to keep the logs outside of Docker's default logging mechanism.

To learn more about logging, visit [Better Stack Community](https://betterstack.com/community/guides/logging/).