Connecting to a Locally Hosted MySQL Database from a Docker Container
When transitioning an application to production, it's desirable to avoid using the container-hosted database. This article addresses how to connect a local MySQL database to an application running in a container using Docker Compose.
Docker Compose Configuration
Your provided Docker Compose configuration demonstrates the use of a separate 'app-db' service for the MySQL database. To connect to a local MySQL database instead, adjust your Compose file as follows:
<code class="yaml">version: '3' services: web-app: ... app-db: image: mysql:8 environment: - MYSQL_ROOT_PASSWORD=password - MYSQL_DATABASE=<database-name> ports: - 3306:3306</code>
Connecting via Hostname
Instead of using 'localhost', which refers to the container's internal hostname, use 'host.docker.internal'. This resolves to the Docker host's IP address, enabling you to connect to your local database.
Linux Configuration
For Linux systems, add the following parameter when starting the Docker container:
<code class="bash">--add-host host.docker.internal:host-gateway</code>
Example Usage
In your web application, replace the database connection information to use 'host.docker.internal' instead of 'localhost'. For example:
db = mysql.connector.connect( host="host.docker.internal", ... )
By implementing these changes, you can successfully connect your local MySQL database to your application running in a Docker container.
The above is the detailed content of How to Connect to a Locally Hosted MySQL Database from a Docker Container?. For more information, please follow other related articles on the PHP Chinese website!