导航菜单
首页 >  MySQL samples Docker Docs  > Use containerized databases

Use containerized databases

Use containerized databasesTable of contents

Using a local containerized database offers flexibility and ease of setup,letting you mirror production environments closely without the overhead oftraditional database installations. Docker simplifies this process, enabling youto deploy, manage, and scale databases in isolated containers with just a fewcommands.

In this guide, you'll learn how to:

Run a local containerized databaseAccess the shell of a containerized databaseConnect to a containerized database from your hostConnect to a containerized database from another containerPersist database data in a volumeBuild a customized database imageUse Docker Compose to run a database

This guide uses the MySQL image for examples, but the concepts can be applied to other database images.

Prerequisites

To follow along with this guide, you must have Docker installed. To install Docker, seeGet Docker.

Run a local containerized database

Most popular database systems, including MySQL, PostgreSQL, and MongoDB, have aDocker Official Image available on Docker Hub. These images are a curated setimages that follow best practices, ensuring that you have access to the latestfeatures and security updates. To get started, visitDocker Hub and search for the database you'reinterested in. Each image's page provides detailed instructions on how to runthe container, customize your setup, and configure the database according toyour needs. For more information about the MySQL image used in this guide, see the Docker HubMySQL image page.

To run a database container, you can use either the Docker Desktop GUI orCLI.

To run a container using the CLI, run the following command in a terminal:

$ docker run --name my-mysql -e MYSQL_ROOT_PASSWORD=my-secret-pw -e MYSQL_DATABASE=mydb -d mysql:latest

In this command:

--name my-mysql assigns the name my-mysql to your container for easierreference.-e MYSQL_ROOT_PASSWORD=my-secret-pw sets the root password for MySQL tomy-secret-pw. Replace my-secret-pw with a secure password of your choice.-e MYSQL_DATABASE=mydb optionally creates a database named mydb. You canchange mydb to your desired database name.-d runs the container in detached mode, meaning it runs in the background.mysql:latest specifies that you want to use the latest version of the MySQLimage.

To verify that you container is running, run docker ps in a terminal

To run a container using the GUI:

In the Docker Desktop Dashboard, select the global search at the top of the window.

Specify mysql in the search box, and select the Images tab if not alreadyselected.

Hover over the msyql image and select Run.The Run a new container model appears.

Expand Optional settings.

In the optional settings, specify the following:

Container name: my-mysqlEnvironment variables:MYSQL_ROOT_PASSWORD:my-secret-pwMYSQL_DATABASE:mydbThe optional settings screen with the options specified.The optional settings screen with the options specified.

Select Run.

Open the Container view in the Docker Desktop Dashboard to verify that yourcontainer is running.

Access the shell of a containerized database

When you have a database running inside a Docker container, you may need toaccess its shell to manage the database, execute commands, or performadministrative tasks. Docker provides a straightforward way to do this using thedocker exec command. Additionally, if you prefer a graphical interface, youcan use Docker Desktop's GUI.

If you don't yet have a database container running, seeRun a local containerized database.

To access the terminal of a MySQL container using the CLI, you can use thefollowing docker exec command.

$ docker exec -it my-mysql bash

In this command:

docker exec tells Docker you want to execute a command in a runningcontainer.-it ensures that the terminal you're accessing is interactive, so you cantype commands into it.my-mysql is the name of your MySQL container. If you named your containerdifferently when you ran it, use that name instead.bash is the command you want to run inside the container. It opens up a bashshell that lets you interact with the container's file system and installedapplications.

After executing this command, you will be given access to the bash shell insideyour MySQL container, from which you can manage your MySQL server directly. Youcan run exit to return to your terminal.

Open the Docker Desktop Dashboard and select the Containers view.In the Actions column for your container, select Show containeractions and then select Open in terminal.

In this terminal you can access to the shell inside your MySQL container, fromwhich you can manage your MySQL server directly.

Once you've accessed the container's terminal, you can run any tools availablein that container. The following example shows using mysql in the container tolist the databases.

# mysql -u root -pEnter password: my-secret-pwmysql> SHOW DATABASES;+--------------------+| Database|+--------------------+| information_schema || mydb|| mysql || performance_schema || sys|+--------------------+5 rows in set (0.00 sec)Connect to a containerized database from your host

Connecting to a containerized database from your host machine involves mapping aport inside the container to a port on your host machine. This process ensuresthat the database inside the container is accessible via the host machine'snetwork. For MySQL, the default port is 3306. By exposing this port, you can usevarious database management tools or applications on your host machine tointeract with your MySQL database.

Before you begin, you must remove any containers you previously ran for thisguide. To stop and remove a container, either:

In a terminal, run docker remove --force my-mysql to remove the containernamed my-mysql.Or, in the Docker Desktop Dashboard, select the Delete icon next to yourcontainer in the Containers view.

Next, you can use either the Docker Desktop GUI or CLI to run the container withthe port mapped.

Run the following command in a terminal.

$ docker run -p 3307:3306 --name my-mysql -e MYSQL_ROOT_PASSWORD=my-secret-pw -e MYSQL_DATABASE=mydb -d mysql:latest

In this command, -p 3307:3306 maps port 3307 on the host to port 3306 in the container.

To verify the port is mapped, run the following command.

$ docker ps

You should see output like the following.

CONTAINER IDIMAGE COMMAND CREATED STATUS PORTSNAMES6eb776cfd73cmysql:latest"docker-entrypoint.s…"17 minutes agoUp 17 minutes33060/tcp, 0.0.0.0:3307->3306/tcpmy-mysql

To run a container using the GUI:

In the Docker Desktop Dashboard, select the global search at the top of the window.

Specify mysql in the search box, and select the Images tab if not alreadyselected.

Hover over the msyql image and select Run.The Run a new container model appears.

Expand Optional settings.

In the optional settings, specify the following:

Container name: my-mysqlHost port for the 3306/tcp port: 3307Environment variables:MYSQL_ROOT_PASSWORD:my-secret-pwMYSQL_DATABASE:mydbThe optional settings screen with the options specified.The optional settings screen with the options specified.

Select Run.

In the Containers view, verify that the port is mapped under thePort(s) column. You should see 3307:3306 for the my-mysqlcontainer.

At this point, any application running on your host can access the MySQL service in the container at localhost:3307.

Connect to a containerized database from another container

Connecting to a containerized database from another container is a commonscenario in microservices architecture and during development processes.Docker's networking capabilities make it easy to establish this connectionwithout having to expose the database to the host network. This is achieved byplacing both the database container and the container that needs to access it onthe same Docker network.

Before you begin, you must remove any containers you previously ran for thisguide. To stop and remove a container, either:

In a terminal, run docker remove --force my-mysql to remove the containernamed my-mysql.Or, in the Docker Desktop Dashboard, select the Delete icon next to yourcontainer in the Containers view.

To create a network and run containers on it:

Run the following command to create a Docker network named my-network.

$ docker network create my-network

Run your database container and specify the network using the --networkoption. This runs the container on the my-network network.

$ docker run --name my-mysql -e MYSQL_ROOT_PASSWORD=my-secret-pw -e MYSQL_DATABASE=mydb --network my-network -d mysql:latest

Run your other containers and specify the network using the --networkoption. For this example, you'll run a phpMyAdmin container that can connectto your database.

Run a phpMyAdmin container. Use the --network option to specify thenetwork, the -p option to let you access the container from your hostmachine, and the -e option to specify a required environment variablefor this image.

$ docker run --name my-phpmyadmin -d --network my-network -p 8080:80 -e PMA_HOST=my-mysql phpmyadmin

Verify that the containers can communicate. For this example, you'll accessphpMyAdmin and verify that it connects to the database.

Openhttp://localhost:8080 to access your phpMyAdmin container.Log in using root as the username and my-secret-pw as the password.You should connect to the MySQL server and see your database listed.

At this point, any application running on your my-network container networkcan access the MySQL service in the container at my-mysql:3306.

Persist database data in a volume

Persisting database data in a Docker volume is necessary for ensuring that yourdata survives container restarts and removals. A Docker volume lets you storedatabase files outside the container's writable layer, making it possible toupgrade the container, switch bases, and share data without losing it. Here’show you can attach a volume to your database container using either the DockerCLI or the Docker Desktop GUI.

Before you begin, you must remove any containers you previously ran for thisguide. To stop and remove a container, either:

In a terminal, run docker remove --force my-mysql to remove the containernamed my-mysql.Or, in the Docker Desktop Dashboard, select the Delete icon next to yourcontainer in the Containers view.

Next, you can use either the Docker Desktop GUI or CLI to run the container with a volume.

To run your database container with a volume attached, include the -v optionwith your docker run command, specifying a volume name and the path where thedatabase stores its data inside the container. If the volume doesn't exist,Docker automatically creates it for you.

To run a database container with a volume attached, and then verify that thedata persists:

Run the container and attach the volume.

$ docker run --name my-mysql -e MYSQL_ROOT_PASSWORD=my-secret-pw -e MYSQL_DATABASE=mydb -v my-db-volume:/var/lib/mysql -d mysql:latest

This command mounts the volume named my-db-volume to the /var/lib/mysql directory in the container.

Create some data in the database. Use the docker exec command to runmysql inside the container and create a table.

$ docker exec my-mysql mysql -u root -pmy-secret-pw -e "CREATE TABLE IF NOT EXISTS mydb.mytable (column_name VARCHAR(255)); INSERT INTO mydb.mytable (column_name) VALUES ('value');"

This command uses the mysql tool in the container to create a table namedmytable with a column named column_name, and finally inserts a value ofvalue.

Stop and remove the container. Without a volume, the table you created wouldbe lost when removing the container.

$ docker remove --force my-mysql

Start a new container with the volume attached. This time, you don't need tospecify any environment variables as the configuration is saved in thevolume.

$ docker run --name my-mysql -v my-db-volume:/var/lib/mysql -d mysql:latest

Verify that the table you created still exists. Use the docker exec commandagain to run mysql inside the container.

$ docker exec my-mysql mysql -u root -pmy-secret-pw -e "SELECT * FROM mydb.mytable;"

This command uses the mysql tool in the container to select all therecords from the mytable table.

You should see output like the following.

column_namevalue

To run a database container with a volume attached, and then verify that thedata persists:

Run a container with a volume attached.

In the Docker Desktop Dashboard, select the global search at the top of the window.

Specify mysql in the search box, and select the Images tab if notalready selected.

Hover over the mysql image and select Run.The Run a new container model appears.

Expand Optional settings.

In the optional settings, specify the following:

Container name: my-mysqlEnvironment variables:MYSQL_ROOT_PASSWORD:my-secret-pwMYSQL_DATABASE:mydbVolumes:my-db-volume:/var/lib/mysqlThe optional settings screen with the options specified.The optional settings screen with the options specified.

Here, the name of the volume is my-db-volume and it is mounted in thecontainer at /var/lib/mysql.

Select Run.

Create some data in the database.

In the Containers view, next to your container select the Showcontainer actions icon, and then select Open in terminal.

Run the following command in the container's terminal to add a table.

# mysql -u root -pmy-secret-pw -e "CREATE TABLE IF NOT EXISTS mydb.mytable (column_name VARCHAR(255)); INSERT INTO mydb.mytable (column_name) VALUES ('value');"

This command uses the mysql tool in the container to create a tablenamed mytable with a column named column_name, and finally inserts avalue of value`.

In the Containers view, select the Delete icon next to yourcontainer, and then select Delete forever. Without a volume, the tableyou created would be lost when deleting the container.

Run a container with a volume attached.

In the Docker Desktop Dashboard, select the global search at the top of the window.

Specify mysql in the search box, and select the Images tab if notalready selected.

Hover over the mysql image and select Run.The Run a new container model appears.

Expand Optional settings.

In the optional settings, specify the following:

Container name: my-mysqlEnvironment variables:MYSQL_ROOT_PASSWORD:my-secret-pwMYSQL_DATABASE:mydbVolumes:my-db-volume:/var/lib/mysqlThe optional settings screen with the options specified.The optional settings screen with the options specified.

Select Run.

Verify that the table you created still exists.

In the Containers view, next to your container select the Showcontainer actions icon, and then select Open in terminal.

Run the following command in the container's terminal to verify that tableyou created still exists.

# mysql -u root -pmy-secret-pw -e "SELECT * FROM mydb.mytable;"

This command uses the mysql tool in the container to select all therecords from the mytable table.

You should see output like the following.

column_namevalue

At this point, any MySQL container that mounts the my-db-volume will be ableto access and save persisted data.

Build a customized database image

Customizing your database image lets you include additional configuration,scripts, or tools alongside the base database server. This is particularlyuseful for creating a Docker image that matches your specific development orproduction environment needs. The following example outlines how to build andrun a custom MySQL image that includes a table initialization script.

Before you begin, you must remove any containers you previously ran for thisguide. To stop and remove a container, either:

In a terminal, run docker remove --force my-mysql to remove the containernamed my-mysql.Or, in the Docker Desktop Dashboard, select the Delete icon next to yourcontainer in the Containers view.

To build and run your custom image:

Create a Dockerfile.

Create a file named Dockerfile in your project directory. For thisexample, you can create the Dockerfile in an empty directory of yourchoice. This file will define how to build your custom MySQL image.

Add the following content to the Dockerfile.

# syntax=docker/dockerfile:1# Use the base image mysql:latestFROM mysql:latest# Set environment variablesENV MYSQL_DATABASE mydb# Copy custom scripts or configuration files from your host to the containerCOPY ./scripts/ /docker-entrypoint-initdb.d/

In this Dockerfile, you've set the environment variable for the MySQLdatabase name. You can also use the COPY instruction to add customconfiguration files or scripts into the container. In thisexample, files from your host's ./scripts/ directory are copied into thecontainer's /docker-entrypoint-initdb.d/ directory. In this directory,.sh, .sql, and .sql.gz scripts are executed when the container isstarted for the first time. For more details about Dockerfiles, see theDockerfile reference.

Create a script file to initialize a table in the database. In thedirectory where your Dockerfile is located, create a subdirectory namedscripts, and then create a file named create_table.sql with thefollowing content.

CREATE TABLE IF NOT EXISTS mydb.myothertable ( column_name VARCHAR(255));INSERT INTO mydb.myothertable (column_name) VALUES ('other_value');

You should now have the following directory structure.

├── your-project-directory/│ ├── scripts/│ │ └── create_table.sql│ └── Dockerfile

Build your image.

In a terminal, change directory to the directory where your Dockerfileis located.

Run the following command to build the image.

$ docker build -t my-custom-mysql .

In this command, -t my-custom-mysql tags (names) your new image asmy-custom-mysql. The period (.) at the end of the command specifies thecurrent directory as the context for the build, where Docker looks for theDockerfile and any other files needed for the build.

Run your image as you did inRun a local containerizeddatabase. This time, specify yourimage's name instead of mysql:latest. Also, you no longer need to specifythe MYSQL_DATABASE environment variable as it's now defined by yourDockerfile.

$ docker run --name my-mysql -e MYSQL_ROOT_PASSWORD=my-secret-pw -d my-custom-mysql

Verify that your container is running with the following command.

$ docker ps

You should see output like the following.

CONTAINER IDIMAGE COMMAND CREATEDSTATUS PORTS NAMESf74dcfdb0e59my-custom-mysql"docker-entrypoint.s…"2 hours agoUp 51 minutes3306/tcp, 33060/tcpmy-mysql

Verify that your initialization script was ran. Run the following command ina terminal to show the contents of the myothertable table.

$ docker exec my-mysql mysql -u root -pmy-secret-pw -e "SELECT * FROM mydb.myothertable;"

You should see output like the following.

column_nameother_value

Any container ran using your my-custom-mysql image will have the tableinitialized when first started.

Use Docker Compose to run a database

Docker Compose is a tool for defining and running multi-container Dockerapplications. With a single command, you can configure all your application'sservices (like databases, web apps, etc.) and manage them. In this example,you'll create a Compose file and use it to run a MySQL database container and a phpMyAdmin container.

To run your containers with Docker Compose:

Create a Docker Compose file.

Create a file named compose.yaml in your project directory. This filewill define the services, networks, and volumes.

Add the following content to the compose.yaml file.

services: db:image: mysql:latestenvironment: MYSQL_ROOT_PASSWORD: my-secret-pw MYSQL_DATABASE: mydbports: - 3307:3306volumes: - my-db-volume:/var/lib/mysql phpmyadmin:image: phpmyadmin/phpmyadmin:latestenvironment: PMA_HOST: db PMA_PORT: 3306 MYSQL_ROOT_PASSWORD: my-secret-pwports: - 8080:80depends_on: - dbvolumes: my-db-volume:

For the database service:

db is the name of the service.image: mysql:latest specifies that the service uses the latest MySQLimage from Docker Hub.environment lists the environment variables used by MySQL toinitialize the database, such as the root password and the databasename.ports maps port 3307 on the host to port 3306 in the container,allowing you to connect to the database from your host machine.volumes mounts my-db-volume to /var/lib/mysql inside the containerto persist database data.

In addition to the database service, there is a phpMyAdmin service. Bydefault Compose sets up a single network for your app. Each container fora service joins the default network and is both reachable by othercontainers on that network, and discoverable by the service's name.Therefore, in the PMA_HOST environment variable, you can specify theservice name, db, in order to connect to the database service. For more details about Compose, see theCompose file reference.

Run Docker Compose.

Open a terminal and change directory to the directory where yourcompose.yaml file is located.

Run Docker Compose using the following command.

$ docker compose up

You can now access phpMyAdmin athttp://localhost:8080 and connect to yourdatabase using root as the username and my-secret-pw as the password.

To stop the containers, press ctrl+c in the terminal.

Now, with Docker Compose you can start your database and app, mount volumes,configure networking, and more, all with a single command.

Summary

This guide introduced you to the essentials of using containerized databases,specifically focusing on MySQL, to enhance flexibility, ease of setup, andconsistency across your development environments. The use-cases covered inthis guide not only streamline your development workflows but also prepare youfor more advanced database management and deployment scenarios, ensuring yourdata-driven applications remain robust and scalable.

Related information:

Docker Hub database imagesDockerfile referenceCompose file referenceCLI referenceDatabase samples

相关推荐: