Connecting to 'localhost' or '127.0.0.1' with a docker-compose setup

Seems to be a common question but with different contexts but I’m having a problem connecting to my localhost DB when using Docker.

If I inspect the mysql container using docker inspect and find the IP address and use this as the DB host as part of the CMS, it runs fine… the only issue is the mysql container IP address changes (upon eachdocker-compose up and if I change wifi networks) so ideally I’d like to use ‘localhost’ or ‘127.0.0.1’ but for some reason this results in a SQLSTATE[HY000] [2002] Connection refused error.

How can I use ‘localhost’ or ‘127.0.0.1’ as the DB hostname in CMS applications so I don’t have to keep changing it as the container IP address changes?

This is my docker-compose.yml file:

version: "3"

services:
  webserver:
    build:
      context: ./bin/webserver
    restart: 'always'
    ports:
      - "80:80"
      - "443:443"
    links:
      - mysql
    volumes:
      - ${DOCUMENT_ROOT-./www}:/var/www/html
      - ${PHP_INI-./config/php/php.ini}:/usr/local/etc/php/php.ini
      - ${VHOSTS_DIR-./config/vhosts}:/etc/apache2/sites-enabled
      - ${LOG_DIR-./logs/apache2}:/var/log/apache2
    networks:
      mynet:
          aliases:
            - rich.dev
  mysql:
    image: 'mysql:5.7'
    restart: 'always'
    ports:
      - "3306:3306"
    volumes:
      - ${MYSQL_DATA_DIR-./data/mysql}:/var/lib/mysql
      - ${MYSQL_LOG_DIR-./logs/mysql}:/var/log/mysql
    environment:
      MYSQL_ROOT_PASSWORD: example
    networks:
      - mynet
  phpmyadmin:
    image: phpmyadmin/phpmyadmin
    links:
      - mysql
    environment:
      PMA_HOST: mysql
      PMA_PORT: 3306
    ports:
      - '8080:80'
    volumes:
      - /sessions
    networks:
      - mynet
networks:
  mynet:

It’s possible to configure static IP addresses for mynet. It should be useful when connecting to services from outside the network when you can’t use symbolic names.

https://fordodone.com/2016/03/30/docker-compose-static-ip-address-in-docker-compose-yml/

From other containers you can use mysql as a host name.

(Since you’ve manually declared a network, the caller needs to be on the same network; if you don’t, Docker Compose will create a network for you. You declared a links: and historically that has the same effect, but it’s unnecessary and discouraged these days.)