Working with Docker Volumes


A Hands-on Lab Guide
Table of Contents
1. Introduction
2. Solution Overview
3. Step-by-Step Implementation
4. Command Reference
5. Conclusion
1. Introduction
This guide demonstrates how to create a Docker container using an NGINX base image with two persistent volumes:
Volume 1: Stores HTML files (/usr/share/nginx/html)
Volume 2: Stores NGINX logs (/var/log/nginx)
Persistent volumes ensure data survives container restarts or deletions.
2. Solution Overview
We will:
Create a Dockerfile defining the NGINX image with volumes
Build and tag the Docker image
Create named volumes for persistence
Run a container with volume mount
Test by modifying the default webpage
3. Step-by-Step Implementation
Step 1: Create a Dockerfile
A. Gain root privileges:
bash
sudo su -
Switches to admin user to avoid permission issues
B. Create and edit the Dockerfile:
bash
vi Dockerfile
Opens Vim editor to create the configuration file
C. Add these instructions:
FROM nginx
VOLUME /usr/share/nginx/html
VOLUME /var/log/nginx
WORKDIR /usr/share/nginx/html
NOTE
FROM: Uses official NGINX image as base
VOLUME: Declares persistent storage paths
WORKDIR: Sets default container working directory
D. Save and exit (:wq in Vim)
Step 2: Build the Docker Image
bash
docker build -t la/nextgen:latest -f Dockerfile .
NOTE
- -t
: Tags the image (name:version)
- -f
: Specifies Dockerfile name
- ‘:’ Uses current directory as build context
Step 3: Create Docker Volumes
For HTML content:
bash
docker volume create nginx-code
For server logs:
bash
docker volume create nginx-logs
NOTE
This creates named volumes managed by Docker
Step 4: Run the Container
bash
docker run -d --name=nextgen-dev -p 80:80 --mount source=nginx-code,target=/usr/share/nginx/html --mount source=nginx-logs,target=/var/log/nginx la/nextgen:latest
NOTE
- -d
: Runs in background
- --name
: Assigns container name
- -p
: Maps host:container ports
- --mount
: Attaches volumes to container paths
Verify it's running:
`bash
docker ps
Step 5: Test the Setup
a. Locate the volume data:
bash
cd /var/lib/docker/volumes/nginx-code/_data/
Docker stores volume contents here by default
b. Edit the webpage:
bash
vi index.html
Add:
html
<p>ANY WELCOME MESSAGE! </p>
c. Access http: //localhost` to see your changes.
4. Command Reference
S/N | Command | Purpose |
1 | Sudo su - | Gain root privileges |
2 | docker build` | Create image from Dockerfile |
3 | Docker volume create | Make persistent storage |
4 | Docker run -- mount | Start container with volumes |
5 | Docker ps | Check running containers |
6. Conclusion
You've now:
- Created a Docker image with persistent storage
- Learned essential Docker commands for volume management
- Verified data persists across container lifecycles
Subscribe to my newsletter
Read articles from Joel Thompson directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by
