Created
September 30, 2024 07:00
-
-
Save slhck/d5539c1ed3e3bd2cb95b69299cc542de to your computer and use it in GitHub Desktop.
Expose a Docker-based Postgres database to localhost
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env bash | |
# | |
# Start a reverse proxy for the Postgres DB, | |
# exposing port 5432 locally. | |
# | |
# To use this, on your local machine, run: | |
# | |
# ssh -t -L 5432:localhost:5432 username@hostname 'cd $HOME/path/to/folder/ && ./dbproxy.sh' | |
set -e | |
SERVICE="database" | |
CONTAINER=$(docker compose ps -q "$SERVICE") | |
NET_NAME=$(docker inspect --format '{{.HostConfig.NetworkMode}}' "$CONTAINER") | |
ALIAS=$(docker inspect --format '{{index .NetworkSettings.Networks "'$NET_NAME'" "Aliases" 0}}' "$CONTAINER") | |
LOCALPORT="5432" | |
PROXY_NAME=dbproxy | |
echo "Exposing $SERVICE on localhost:$LOCALPORT" | |
docker ps -q --filter "name=$PROXY_NAME" | grep -q . && docker stop "$PROXY_NAME" | |
docker run \ | |
--rm \ | |
--name "$PROXY_NAME" \ | |
--net "$NET_NAME" \ | |
--publish "$LOCALPORT:1234" \ | |
alpine/socat TCP-LISTEN:1234,fork "TCP-CONNECT:$ALIAS:$LOCALPORT" & | |
pid=$! | |
echo "Ready! Press Ctrl-C to close." | |
trap "kill $pid" INT HUP | |
wait $pid |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment