Use tcp instead of unix sockets for DB containers

This is part of the Semicolon&Sons Code Diary - consisting of lessons learned on the job. You're in the containerization category.

Last Updated: 2024-11-23

I could not connect to a mysql database running locally in docker. Error was: Nodename not found.

Here was my docker-compose config:

services:
  db:
    image: mysql:5.7.28
    container_name: db
    restart: unless-stopped
    tty: true
    ports:
      - "3306:3306"
    environment:
      MYSQL_DATABASE: mydb_test
      MYSQL_ROOT_PASSWORD: password
      SERVICE_TAGS: test
      SERVICE_NAME: mysql
    volumes:
      - dbdata:/var/lib/mysql/
      - ./mysql/my.cnf:/etc/mysql/my.cnf
    networks:
      - app-network

Next I tried manually connecting from my command line with:

$ mysql -P 3306 -u root -p mydb_test

This failed with:

ERROR 2002 (HY000): Can't connect to local MySQL server through socket '/tmp/mysql.sock' (2)

Ah! So unix sockets are not available for this docker setup! Therefore I tried tcp and it worked

$ mysql -P 3306 --protocol=tcp -u root -p project_s_test