Setting Up a MySQL Docker Container for Development: A Comprehensive Guide
Why Docker? Docker, a powerful tool for creating, deploying, and running applications by using containers, offers a solution. This article guides you through efficiently setting up a single MySQL container, importing a database schema, and establishing a secure connection using environment variables within your application.
Setting Up Your MySQL Container
Our journey begins by fetching the official MySQL image from Docker Hub.
docker pull mysql
Run MySQL Container
Next, we create a MySQL container with a predefined root password. For persistence beyond the lifetime of the container, we mount a volume from the host to the container's data directory
docker run --name mysqlContainer -e MYSQL_ROOT_PASSWORD=secretpassword -d mysql
# Or with volume for data persistence
docker run --name mysqlContainer -e MYSQL_ROOT_PASSWORD=secretpassword -v /path/to/host/directory:/var/lib/mysql -d mysql
Accessing the MySQL Shell
To interact with your MySQL instance, access the shell as follow
docker exec -it mysqlContainer mysql -u root -p
After entering the password, you can explore your MySQL server. Remember to exit; once done.
Importing Your Database
Often, you'll need to import a pre-existing database. After copying your SQL dump into the container:
领英推荐
docker cp /path/to/directory/dump.sql mysqlContainer:/tmp/database.sql
You can import it using as
#Option A
docker exec -it mysqlContainer bash
mysql -u root -p<secretpassword> < /tmp/database.sql
#Option B
docker exec -it mysqlContainer bash
mysql -u root -p<secretpassword>
source /tmp/database.sql
Find the Container's IP Address
After populating database, the next step is to connect your application. You'll need the container's IP address.
docker inspect container_id | grep IPAddress
# Or
docker inspect -f '{{range .NetworkSettings.Networks}}{{.IPAddress}}{{end}}' container_id
With the IP address, configure your application's database connection as follows:
DB_CONNECTION=mysql
DB_HOST=CONTAINER_IP
DB_PORT=3306
DB_DATABASE=DB_NAME
DB_USERNAME=root
DB_PASSWORD=secretpassword
Replace CONTAINER_IP, DB_NAME, and secretpassword with your container's IP, your database name, and the root password you set earlier.
Remember, while the root account and simple passwords are convenient for development, always use more secure settings for production environments. Happy coding! Have fun ?? ??. Find me on Github, Medium.
Have you tried using Docker for managing your MySQL databases? Share your experiences and tips in the comments below!