On Linux, containers live in separate network namespaces, so localhost or 127.0.0.1 on the container is not localhost on the host. I'm not sure about other OSes. You could expose a port to the host like this:
docker run -p 3306:3306 mysql
Then you can access it from any container at the host IP address, which for the default network is 172.17.0.1:3306. You can add -p many times, read the docs here: https://docs.docker.com/
All that the -p does on Linux, is essentially:
sudo iptables -t nat -A DOCKER \! -i docker0 -p tcp --dport 3306 -j DNAT --to 172.17.0.2:3306
(Or whatever your mysql container IP address is.) Docker compose and similar utilities make containers able to see each other with --link eg.
docker run --link web --link mysql:localmysql app
The only thing this does is to put the correct IP address for the container in a file called /etc/hosts inside the container (but this might change in future.)
If you want to use --link, all containers need to be on the same network. You can connect them while running with:
docker network connect mynet web
The main reason for doing this is because the containers don't have fixed IP addresses. You can do:
docker run --network mynet --ip 172.18.0.10 -d app
To give your container a static IP - and then just use that instead of the name. The docker team keeps changing how things work, so you might need to run additional commands to allow different networks to connect to each other.
You can of course also do all of this manually, on Linux, using the firewall, on the host machine. (Start learning about it here: https://www.google.com/search?q=iptables (Also look at the Images tab!)
iptables -nvxL # shows the filter table
iptables -nvxL -t nat # shows the NAT table where port forwarding is done
To dynamically forward a port to a container, get its IP address, eg 172.18.0.10, then:
iptables -t nat -A POSTROUTING -p tcp --dport 1234 -j DNAT --to 172.18.0.10:4567
Be keenly aware that if you do this, and your container restarts, or gets another IP address, that this will not automatically update, and unless you use iptables-save and iptables-restore in your startup and cron scripts, these manually created rules will disappear. Also that the docker command and compose scripts won't know about any configuration that you manually add like this.
If you really want localhost in your container to point somewhere else, you can edit /etc/hosts inside the container, and change the IP address of localhost - be very keenly aware that other things might break, because localhost is supposed to point to the same host, not another one, so there will be unintended consequences at some point.