shantanuo
shantanuo

Reputation: 32294

connect to mysql database from docker container

I have this docker file and it is working as expected. I have php application that connects to mysql on localhost.

# cat Dockerfile
FROM tutum/lamp:latest
RUN rm -fr /app
ADD crm_220 /app/
ADD crmbox.sql /
ADD mysql-setup.sh /mysql-setup.sh
EXPOSE 80 3306
CMD ["/run.sh"]

When I tried to run the database as separate container, my php application is still pointing to localhost. When I connect to the "web" container, I am not able to connect to "mysql1" container.

# cat docker-compose.yml
web:
  build: .
  restart: always
  volumes:
    - .:/app/
  ports:
    - "8000:8000"
    - "80:80"
  links:
    - mysql1:mysql

mysql1:
  image: mysql:latest
  volumes:
    - "/var/lib/mysql:/var/lib/mysql"
  ports:
    - "3306:3306"
  environment:
    MYSQL_ROOT_PASSWORD: secretpass

How does my php application connect to mysql from another container?

This is similar to the question asked here...

Connect to mysql in a docker container from the host

I do not want to connect to mysql from host machine, I need to connect from another container.

Upvotes: 5

Views: 22437

Answers (2)

Imran
Imran

Reputation: 1902

For me, the name resolutions is never happening. Here is my docker file, and I was hoping to connect from app host to mysql, where the name is mysql and passed as an env variable to the other container - DB_HOST=mysql

version: "2"
services:

  app:
    build:
      context: ./
      dockerfile: /src/main/docker/Dockerfile
    image: crossblogs
    environment:
      - DB_HOST=mysql
      - DB_PORT=3306
    ports:
      - 8080:8080
    depends_on:
      - mysql

  mysql:
    image: mysql:5.7.20
    environment:
      - MYSQL_USER=root
      - MYSQL_ALLOW_EMPTY_PASSWORD=yes
      - MYSQL_DATABASE=crossblogs
    ports:
      - 3306:3306
    command: mysqld --lower_case_table_names=1 --skip-ssl --character_set_server=utf8 --explicit_defaults_for_timestamp

Upvotes: 0

Cortwave
Cortwave

Reputation: 4917

At first you shouldn't expose mysql 3306 port if you not want to call it from host machine. At second links are deprecated now. You can use network instead. I not sure about compose v.1 but in v.2 all containers in common docker-compose file are in one network (more about networks) and can be resolved by name each other. Example of docker-compose v.2 file:

version: '2'
services:
  web:
    build: .
    restart: always
    volumes:
      - .:/app/
    ports:
      - "8000:8000"
      - "80:80"
  mysql1:
    image: mysql:latest
    volumes:
      - "/var/lib/mysql:/var/lib/mysql"
    environment:
      MYSQL_ROOT_PASSWORD: secretpass

With such configuration you can resolve mysql container by name mysql1 inside web container.

Upvotes: 5

Related Questions