Skip to content

Instantly share code, notes, and snippets.

@pkqk
Last active October 26, 2015 15:44
Show Gist options
  • Save pkqk/a24b6e64b923ed613cbb to your computer and use it in GitHub Desktop.
Save pkqk/a24b6e64b923ed613cbb to your computer and use it in GitHub Desktop.
dynamic rails config files
ODC_REDIS_SERVER_URL="redis://$(docker-service odc-redis 6379)"␍

I've started running app services on docker so I don't have to deal with installing shit all the time.

However that means each time you start up a service it comes up on a different random port unless you deliberately map one. But dynamic ports are easier so provided you give the containers for each service a name then they are inspectable using the docker commands.

docker-machine ip default gives you the ip address of the default docker host. docker port name-of-container will list all mapped ports from internal port number to host port number

3306/tcp -> 0.0.0.0:32769

docker inspect --format="{formatstr}" name-of-container will let you pick elements out of the Go formatted data structure

docker inspect --format="{{(index (index .NetworkSettings.Ports \"3306/tcp\") 0).HostPort}}" name-of-mysql

That's a bit unwieldy so I made a docker-service script that will give you the ip, port or ip:port for a container-name and standard port number eg.

$ docker-service odc-mysql 3306 ip
192.168.99.100
$ docker-service odc-mysql 3306 port
32769
$ docker-service odc-mysql 3306 addr
192.168.99.100:32769

dotenv lets you run commands when setting variables by using $(cmd) and all .yml files in rails let you embed ERB so you can use ruby backticks to execute shell commands there and get the output.

development: &dev
host: <%= `docker-service odc-mysql 3306 ip` %>
port: <%= `docker-service odc-mysql 3306 port` %>
#!/bin/bash
set -e
SERVICE=$1
PORT=$2
OUTPUT=${3:-addr}
IP=$(docker-machine ip default)
MAPPED_PORT=$(docker inspect --format="{{(index (index .NetworkSettings.Ports \"${PORT}/tcp\") 0).HostPort}}" ${SERVICE})
case $OUTPUT in
ip)
echo "${IP}"
;;
port)
echo "${MAPPED_PORT}"
;;
*)
echo "${IP}:${MAPPED_PORT}"
esac
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment