Share Data Between Docker Container and Host featured image

How To Share Data Between a Docker Container and a Host

Introduction

Generally, Docker containers only run for a certain period of time – the time it takes to run the command. The data that is available inside the container can only be accessed from within the container during the runtime.

Docker volumes can be used for accessing the files easily and storing them for a longer period. For example, if you have an Nginx web server and you want to store the logs for audits, you can use a Docker volume to store the logs from the container in your host machine.

In this tutorial, you will learn how to share data between the inside of the Docker container and the host machine. 

Prerequisites

For this tutorial, you will need the following prerequisites:

Step 1 – Bind Mount a Volume

You can create a directory named logs in your current user’s home directory and bind-mount it to /var/log/nginx in the Nginx container using the following command:

Here is more detailed information about this command:

  • --name=nginx gives a name to the container for easy reference.
  • -d argument detaches the process and runs it in the background.
  • -v hostPath:containerPath maps the host path and the container path to bind the mount.
  • -p hostPort:containerPort argument maps the container’s port to the host port.
  • nginx at the end of the line is the name of the image that should be used to spawn up the container.
Note: Always use / or ~/ to start the hostPath, otherwise the -v argument considers the path to be the name of the volume and doesn’t bind the mount.

Step 2 – Accessing Data on the Host

Now, you have an Nginx container running on your server, and port 5000 of your server maps to port 80 of the Nginx. You can open the port in the web browser with the following URL:

nginx homepage

In the ~/logs directory, you will see access.log and error.log files. You can see the logs by using the cat command:

You can also check the log directory ~/logs on your host machine and find the logs file of Nginx. Moreover, if you make any changes in the logs folder, they would also reflect in the container’s /var/log/nginx folder as well.

Conclusion

In this tutorial, you have learned how to share data between the inside of the Docker container and the host machine. This is essential in development environments where analyzing logs is a must for debugging.

For more resources on Docker on our blog, you can check out the following:

Happy Computing!