0

I'm pretty new to Docker but am trying to use it to clean up some of my projects. One such project is a fairly simple PHP/MySQL application. I've "docker-ized" the app by adding a docker-compose.yml with db and php services. Here's my docker-compose.yml:

version: '2'
services:
  php:
    build: .
    ports:
      - "80:80"
      - "443:443"
    volumes:
      - ./public_html:/var/www/html
    links:
      - db
  db:
    image: mysql:5.5
    ports:
      - "3306:3306"
    environment:
        MYSQL_USER: root
        MYSQL_PASSWORD:
        MYSQL_ROOT_PASSWORD:
        MYSQL_ALLOW_EMPTY_PASSWORD: 'yes'
    volumes:
      - /c/dockerdata:/var/lib/mysql

This works correctly however I have to change all my PHP scripts to use "db" instead of "localhost" when connecting to the mysql database. I'm adding the docker stuff just as a way to clean up development so I'm trying to avoid changing the PHP code itself. Is there a way I can configure this so I'm able to use localhost or 127.0.0.1 to connect?

2 Answers 2

1

Docker doesn't allow you to modify /etc/hosts on containers Known issue

You can edit /etc/hosts with entrypoint option

Create entrypoint.sh script

#!/bin/bash
cp /etc/hosts /tmp/hosts
sed -e '/localhost/ s/^#*/#/' -i /tmp/hosts
cp /tmp/hosts /etc/hosts
# add your command here to run php application

Add execute permissions to entrypoint.sh

chmod +x entrypoint.sh

Add below two lines to Dockerfile

ADD entrypoint.sh /entrypoint.sh
ENTRYPOINT /entrypoint.sh

Now do the step 2) from my previous answer.

Sign up to request clarification or add additional context in comments.

Comments

1

You can achieve this using below two steps

1) Add below CMD to your Dockerfile

CMD sed -e '/localhost/ s/^#*/#/' -i /etc/hosts

2) Replace 'db' with 'localhost' in docker-compose.yml

links: - db db: image: mysql:5.5

as

links: - localhost localhost: image: mysql:5.5

1 Comment

I get the following: php_1 | sed: cannot rename /etc/sed6KFTSI: Device or resource busy

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.