Home > Database > Mysql Tutorial > body text

How to Connect to a Locally Hosted MySQL Database from a Docker Container?

Susan Sarandon
Release: 2024-10-26 18:42:30
Original
194 people have browsed it

How to Connect to a Locally Hosted MySQL Database from a Docker Container?

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>
Copy after login

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>
Copy after login

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",
    ...
)
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!