Skip to content

Instantly share code, notes, and snippets.

@sngmn451
Created February 9, 2025 16:05
Show Gist options
  • Save sngmn451/663f421fdeff49f6180ba25d740d0684 to your computer and use it in GitHub Desktop.
Save sngmn451/663f421fdeff49f6180ba25d740d0684 to your computer and use it in GitHub Desktop.
Set up postgres:17-alpine with tunnel for Cloudflare Hyperdrive

Cloudflare Hyperdrive Tunnel to Postgres on Docker

How to run

Environment description

docker run -p 5432:5432 -d -e ARCH=${"arm64"|"amd64"} -e POSTGERS_PASSWORD=${pg_password} -e CF_TUNNEL_TOKEN=${cf_tunnel_token} ${pg-name}

Source

# Use PostgreSQL 17 Alpine as base
FROM postgres:17-alpine
# Set environment variables (change as needed)
ENV POSTGRES_USER=postgres
ENV POSTGRES_DB=postgres
ENV POSTGRES_PASSWORD=password
ENV CF_TUNNEL_TOKEN=
ENV ARCH=amd64
# Add locale environment variables
ENV LANG=en_US.utf8
ENV LC_ALL=en_US.utf8
# Install locale dependencies
RUN apk add --no-cache musl-locales musl-locales-lang
# Create a directory for SSL certificates
RUN mkdir -p /var/lib/postgresql/ssl
# Copy SSL certificate and key
COPY server.crt /var/lib/postgresql/ssl/server.crt
COPY server.key /var/lib/postgresql/ssl/server.key
# Set permissions for security
RUN chmod 600 /var/lib/postgresql/ssl/server.* && \
chown postgres:postgres /var/lib/postgresql/ssl/server.*
# Create custom postgresql.conf
RUN echo "ssl = on" >> /usr/local/share/postgresql/postgresql.conf.sample && \
echo "ssl_cert_file = '/var/lib/postgresql/ssl/server.crt'" >> /usr/local/share/postgresql/postgresql.conf.sample && \
echo "ssl_key_file = '/var/lib/postgresql/ssl/server.key'" >> /usr/local/share/postgresql/postgresql.conf.sample && \
echo "ssl_prefer_server_ciphers = on" >> /usr/local/share/postgresql/postgresql.conf.sample && \
echo "ssl_min_protocol_version = TLSv1.2" >> /usr/local/share/postgresql/postgresql.conf.sample
# Create or modify pg_hba.conf to require SSL and allow local connections
RUN echo "# TYPE DATABASE USER ADDRESS METHOD" > /usr/local/share/postgresql/pg_hba.conf.sample && \
echo "local all all trust" >> /usr/local/share/postgresql/pg_hba.conf.sample && \
echo "hostssl all all all scram-sha-256" >> /usr/local/share/postgresql/pg_hba.conf.sample && \
echo "host all all 127.0.0.1/32 scram-sha-256" >> /usr/local/share/postgresql/pg_hba.conf.sample && \
echo "host all all ::1/128 scram-sha-256" >> /usr/local/share/postgresql/pg_hba.conf.sample
# Install Cloudflare Tunnel
RUN wget https://github.com/cloudflare/cloudflared/releases/latest/download/cloudflared-linux-$ARCH -O /usr/bin/cloudflared && chmod +x /usr/bin/cloudflared
# Expose PostgreSQL port for local connections
EXPOSE 5432
CMD ["sh", "-c", "docker-entrypoint.sh postgres & \
sleep 5 && \
exec cloudflared tunnel --no-autoupdate run --token $CF_TUNNEL_TOKEN"]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment