Skip to content

Instantly share code, notes, and snippets.

@bortels
Last active August 29, 2015 14:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bortels/d33bb54d2f98f9e5eb21 to your computer and use it in GitHub Desktop.
Save bortels/d33bb54d2f98f9e5eb21 to your computer and use it in GitHub Desktop.
Exposing a port on a running docker container

So - that was just complex enough that it might be nice to document and share it.

So - I am using docker and --link to expose a redis database to only the apps that use it. Which (as of now) is fine, so long as those apps are on the same host. But - I wanted to use the redis 'slaveof' command to quickly replicate the data to another redis running on a different host. Yes - I could grab the db from disk, scp, and restore. But it's handy to be able to quickly spawn a new copy elsewhere. I could not simply restart the original redis container exposing ports, because it is prod with people reading/writing to it.

So - The solution that works is: Run a new container, exposing the port you want, linked to the original container - and use socat to bridge the internal link to the external port.

I have a docker container I called "exposeredis". The Dockerfile is:

FROM debian:7
RUN apt-get update && \
    apt-get -y install socat && \
    apt-get clean
USER nobody
CMD socat -dddd TCP-LISTEN:6379,reuseaddr,fork TCP:redis:6379

I build it with "docker build -t exposeredis ."

Now, I can run "docker run -it --rm --link mylocalrediscontainer:redis -p 6379:6379 exposeredis" - where "mylocalrediscontainer" is the name of my local linked-to redis container.

Now, we have the original redis, and a new container linked to it, exposing that port, running socat to connect the two.

I go to my new box, run "docker run -d --name mynewredis redis:latest" (the name you choose may vary), then

docker run -it --link mynewredis:redis --rm redis sh -c 'exec redis-cli -h "$REDIS_PORT_6379_TCP_ADDR" -p "$REDIS_PORT_6379_TCP_PORT"'

That ugly bit (I changed "mynewredis" to $1 and put it in a convenience shell script) runs a new redis container running redis-cli, linked to our new local redis.

Finally - I type "slaveof 1.2.3.4" to replicate the data - replacing 1.2.3.4 with the name of the original host. "keys *" will show you the data copied over. This will continue to update until you run "slaveof no one" to sever the link. You can then kill the original exposeredis container, it's job done.

Credits:

This scheme is stolen almost verbatim from this post http://stackoverflow.com/questions/19897743/exposing-a-port-on-a-live-docker-container

with a few more details re. the specific redis use-case and such for the slower people, like myself. :-)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment