Volume Mounting
The -v
parameter in docker run
allows us to mount volumes, sharing data between the host and the container. This is incredibly useful for persisting data or for providing configuration files to the container.
Let's start by creating a simple directory structure on our host:
mkdir -p ~/project/nginx-data
echo "<html><body><h1>Hello from mounted volume</h1></body></html>" > ~/project/nginx-data/index.html
These commands do the following:
- Create a new directory
nginx-data
inside the project
folder in your home directory.
- Create a simple HTML file named
index.html
inside this new directory.
Now, let's run an Nginx container and mount this directory:
docker run -d --name nginx-volume -p 8081:80 -v ~/project/nginx-data:/usr/share/nginx/html nginx
Let's break down this command:
docker run
: This is the command to run a new container.
-d
: This runs the container in detached mode (in the background).
--name nginx-volume
: This assigns the name "nginx-volume" to our container.
-p 8081:80
: This maps port 8081 on the host to port 80 in the container.
-v ~/project/nginx-data:/usr/share/nginx/html
: This mounts the nginx-data
directory from our host to the /usr/share/nginx/html
directory in the container. This is where Nginx looks for content to serve.
nginx
: This is the name of the image we're using to create the container.
Now, let's verify that the custom page is being served:
curl http://localhost:8081
You should see the content of your custom HTML file: "Hello from mounted volume!"
If you don't see your custom content, here are a few things to check:
- Make sure the
~/project/nginx-data/index.html
file exists on your host system.
- Check that the container is running:
docker ps | grep nginx-volume
- Check the Nginx logs for any errors:
docker logs nginx-volume
This method of mounting a host directory to a container is called a bind mount. It's a straightforward way to share files between the host and the container. Here are a few key points to remember:
- The host directory path must be an absolute path.
- If the host directory doesn't exist, Docker will create it automatically.
- Any changes made to files in this directory (either on the host or in the container) will be immediately visible to both the host and the container.
- Be careful with permissions: the container runs as root by default, which might create files that your host user can't modify.
By using this method, we avoid the "not a directory" error because we're mounting a directory, not a single file. This approach gives you more flexibility to add, remove, or modify files without having to recreate the container.