Create volume:
Check if volume exists:
Inspect metadata of volume:
Run container with mounting this persistent 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:
If you need the container's IP for network interaction, you can find it as follows:
Most likely you will see a network named bridge. Let's inspect its settings: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: