Skip to content

Instantly share code, notes, and snippets.

@jakobii
Forked from mrw34/postgres.sh
Last active April 1, 2021 17:36
Show Gist options
  • Save jakobii/20a9992161aeb27b0a917d58e416b5c6 to your computer and use it in GitHub Desktop.
Save jakobii/20a9992161aeb27b0a917d58e416b5c6 to your computer and use it in GitHub Desktop.
Enabling SSL for PostgreSQL in Docker
#!/bin/bash
set -e
sudo rm -f server.req privkey.pem server.key server.crt
# https://www.postgresql.org/docs/11/ssl-tcp.html
openssl req -new -text -passout pass:abcd -subj /CN=localhost -out server.req -keyout privkey.pem
openssl rsa -in privkey.pem -passin pass:abcd -out server.key
openssl req -x509 -in server.req -text -key server.key -out server.crt
chmod og-rwx server.key
# https://stackoverflow.com/a/55072885/7407752
# debian conainters
test $(uname -s) == Linux && sudo chown 999 server.key
# apline containers
# test $(uname -s) == Linux && chown 70 server.key
#!/bin/bash
# sutable for development environments
# default username: postgres
set -e
container_name="pg"
docker_image="postgres" #https://hub.docker.com/_/postgres
# check that user provided password
if [[ -z "$1" ]]
then
echo "you must specify a new postgres password for the user 'postgres'."
echo "example: ./pg.sh <NEW_PASSWORD>"
exit 1
fi
# delete the container if it already exists.
if [[ ! -z $(docker ps -a -q --filter name=$container_name) ]]
then
echo "deleting existing container '$container_name'"
docker rm -f $container_name
fi
# https://www.postgresql.org/docs/current/auth-trust.html
# Use 'POSTGRES_HOST_AUTH_METHOD=trust' instead of 'POSTGRES_PASSWORD=<password>'
# to allow passwordless connections.
docker run \
-d \
--name $container_name \
-e POSTGRES_PASSWORD=$1 \
-v "$(pwd)/server.crt:/var/lib/postgresql/server.crt:ro" \
-v "$(pwd)/server.key:/var/lib/postgresql/server.key:ro" \
-p 5432:5432 \
$docker_image \
-c ssl=on \
-c ssl_cert_file=/var/lib/postgresql/server.crt \
-c ssl_key_file=/var/lib/postgresql/server.key
# ctr-c to exit the logs. exiting will not stop the container.
docker logs -f $container_name
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment