Docker compose – how to access database?

I created a MySQL Database via docker (and docker compose command) using this configuration:

version: '3.8'
services:
  db:
    image: mysql
    volumes:
      - ./data/mysql:/var/lib/mysql
    ports:
      - '3306:3306'
    environment:
      MYSQL_ROOT_PASSWORD: 'root'
      MYSQL_DATABASE: 'test'

I tried to access http://localhost:3306 but it tells me that the page is currently not working. Is the link I am using wrong or can you tell me how I can access the database?

>Solution :

The URL http://localhost:3306 will not work for accessing the MySQL database as it is the port that MySQL uses to communicate with other services, not a web server port.

To access the MySQL database, you can use a MySQL client tool such as MySQL Workbench or the command-line tool mysql. Here are the steps to access the database using mysql command-line tool:

  1. Open a terminal or command prompt.
  2. Enter the command mysql -h localhost -u root -p and press enter.
  3. You will be prompted to enter the password for the MySQL root user. Enter the password ‘root’ that you set in the docker-compose.yml file.
  4. Once you have successfully logged in, you can run MySQL queries to create tables, insert data, and perform other operations on the database.

Note that when you run the docker-compose up command, it may take a few moments for the database to start up fully before you can connect to it.

Leave a Reply