0

I run a MySQL container with --net=host option.

So now i can make unit test using:g:

self.db = MySQLdb.connect(host="127.0.0.1", user="XYZ", passwd="XYZ", db="TEST_DB")

The problem is when I try to dockerize my unit test, linking the container with my MySQL container, the 127.0.0.1 IP is not valid. I need to use the real ip for the MySql container, or use the DNS (/etc/hosts file).

So I need to alter the ip 127.0.0.1 for the name of the MySQL host.

I imagine that there is a better way to do this? I can, for example, alter the /etc/hosts file of my development enviroment.

1 Answer 1

1

Docker links update the /etc/hosts file in the linked containers.

Use the name of the container you have linked to (find it in the /etc/hosts file) to reference the database in your tests.

self.db = MySQLdb.connect(host="db-container-name", user="XYZ", passwd="XYZ", db="TEST_DB")

docker-compose will also do this for you (it's just a wrapper for Docker and uses links underneath), or you can use the --add-host flag to manually add an entry to a container's /etc/hosts file as per this:

$ docker run -it --add-host db-static:86.75.30.9 ubuntu cat /etc/hosts
172.17.0.22     09d03f76bf2c
fe00::0         ip6-localnet
ff00::0         ip6-mcastprefix
ff02::1         ip6-allnodes
ff02::2         ip6-allrouters
127.0.0.1       localhost
::1             localhost ip6-localhost ip6-loopback
86.75.30.9      db-static
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks! But how can I use it on my development envrimoment. I need to connect to this container on my enviroment. What host do i use? I run docker run --name=XYZ --net=host xpto/xpto, and the try to connect using XYZ. If i put XYZ on my hosts file, it works. Is it the best practice?
Ok! I will try to put --add-host. I read it again, and it alter the hosts file of the container.

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.