Mohammad Yazdian
Mohammad Yazdian

Reputation: 37

Cannot connect to MySQL docker container in localhost

I installed Docker on my Ubuntu system and made a MySQL container:

version: '3.8'

services:
  MySQL:
    container_name: MySQL
    image: mysql:8.0.19
    volumes:
      - mysql-volume:/var/lib/mysql
    restart: always
    environment:
      MYSQL_ROOT_PASSWORD: pskPSK258##
      MYSQL_DATABASE: wordpress
      MYSQL_USER: wordpress
      MYSQL_PASSWORD: pskPSK258##
    command: --default-authentication-plugin=mysql_native_password

volumes:
  mysql-volume:
    name: mysql-volume
    driver: local

When the container is running, I can't connect to it using local hosts or 127.0.0.1. But when I get the IP address of the MySQL container with 'Docker inspect MySQL', I can connect to the MySQL. How can I connect to the database using the address 127.0.0.1?

Upvotes: 0

Views: 481

Answers (1)

Ali Tou
Ali Tou

Reputation: 2205

In order to be accessible from your host, you need to bind your container's port into your host's port:

services:
  MySQL:
    image: mysql/mysql-server:8.0.19
    ports:
      - "3306:3306"  # or "127.0.0.1:3306:3306" to only bind to localhost

The ports section is in HOST_PORT:CONTAINER_PORT or HOST_IP:HOST_PORT:CONTAINER_PORT format.

Upvotes: 1

Related Questions