Home >Database >Mysql Tutorial >How to Connect a Local MySQL Database to a Docker Container Without Changing Container Configuration?

How to Connect a Local MySQL Database to a Docker Container Without Changing Container Configuration?

Barbara Streisand
Barbara StreisandOriginal
2024-10-29 16:36:02898browse

How to Connect a Local MySQL Database to a Docker Container Without Changing Container Configuration?

Connecting a Local MySQL Database to a Docker Container

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.

Modifying docker-compose.yml

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:

  1. Remove the "app-db" service from the docker-compose.yml file.
  2. Add an "environment" section to the "web-app" service, where the database connection details are specified:
<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>

Ensuring Host Resolution

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.

Connecting to the External Database

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn