Home >Database >Mysql Tutorial >How to Connect a Local MySQL Database to a Docker Container Without Changing Container Configuration?
When transitioning applications to production using a Dockerized setup, there may be a desire to avoid the use of container-based databases. This article explores how to connect a locally hosted MySQL database to an application running within a Docker container, without modifying the container's database configuration.
The provided docker-compose.yml file includes a service named "app-db" that initializes a MySQL database within the container. To connect the application to an external MySQL database instead:
<code class="yaml">version: '3' services: web-app: build: context: . dockerfile: web-app/Dockerfile ports: - 8080:8080 environment: - MYSQL_HOST=host.docker.internal - MYSQL_PORT=3306 - MYSQL_USER=username - MYSQL_PASSWORD=password - MYSQL_DATABASE=database_name</code>
For Linux systems, Docker containers are isolated from the host's network configuration. To allow the web application to resolve the host.docker.internal address, the container must be started with the "--add-host host.docker.internal:host-gateway" parameter:
<code class="sh">docker run --add-host host.docker.internal:host-gateway ...</code>
This parameter ensures that the container can resolve host.docker.internal to the host's IP address.
With the modified docker-compose.yml and container configuration in place, the web application should be able to connect to the locally hosted MySQL database as specified in the environment variables.
The above is the detailed content of How to Connect a Local MySQL Database to a Docker Container Without Changing Container Configuration?. For more information, please follow other related articles on the PHP Chinese website!