Skip to content

Create volume:

docker volume create name-of-volume

Check if volume exists:

docker volume list

Inspect metadata of volume:

docker volume inspect name-of-volume

Run container with mounting this persistent volume:

docker run --name app-volume -p 8080:8080 -d -v name-of-volume:/app/data app-volume

Lesson example

Now let's build and run the container:

docker build . -f Dockerfile.mysql -t my-sql:1.0
docker run  -d -p 3306:3306 --name my-mysql -v my-mysql-data:/var/lib/mysql my-sql:1.0

In the command above, we did not create a new volume. If you don't specify an existing volume, Docker will create it automatically. You can verify this:

docker volume list

If you need the container's IP for network interaction, you can find it as follows:

docker network list
Most likely you will see a network named bridge. Let's inspect its settings:

docker network inspect bridge

Example of MySQL Dockerfile:

# Use the official MySQL image from Docker Hub
FROM mysql:latest

# Environment variables for MySQL configuration
ENV MYSQL_ROOT_PASSWORD=1234
ENV MYSQL_DATABASE=app_db
ENV MYSQL_USER=app_user
ENV MYSQL_PASSWORD=1234

# Expose port 3306 for MySQL connections
EXPOSE 3306

# Set the data directory as a volume
VOLUME /var/lib/mysql

# Copy SQL initialization script to set up the database and user
COPY init.sql /docker-entrypoint-initdb.d/

init.sql:

GRANT ALL PRIVILEGES ON app_db.* TO 'app_user'@'%';

-- Use the 'app' database
USE app_db;

-- Create a table to store counter data
CREATE TABLE counter (
   id INT AUTO_INCREMENT PRIMARY KEY,
   value INT
);