How to connect an external MySQL database in Docker?
You can use Docker containers to connect to an external MySQL database, here are some steps:
- Firstly, make sure you have installed Docker and Docker Compose.
- Create a Docker Compose file, for example docker-compose.yml, and add the following content to it.
version: '3'
services:
app:
build: .
ports:
- 8080:8080
environment:
- MYSQL_HOST=my_external_mysql
depends_on:
- db
db:
image: mysql:latest
environment:
- MYSQL_ROOT_PASSWORD=your_mysql_root_password
ports:
- 3306:3306
In this example, we have defined two services: app and db. The app service is your application or container, while the db service is an external MySQL database.
- Build and launch both of these services. In the terminal, navigate to the directory where the Docker Compose file is located and then run the following command:
docker-compose up --build
This will create and start both services. Your application will run on localhost:8080 and can connect to an external MySQL database using the MYSQL_HOST environment variable.
- host name of MySQL
For example, by using Python along with the MySQL Connector:
import mysql.connector
mydb = mysql.connector.connect(
host=os.environ['MYSQL_HOST'],
user="your_mysql_user",
password="your_mysql_password"
)
print(mydb)
This is a simple example that you can adjust according to your needs.
This way, you will be able to connect to an external MySQL database through Docker. Make sure you have provided the correct database credentials and connection information.