{"id":35211200,"url":"https://github.com/chaddyc/pgbouncer","last_synced_at":"2026-04-07T04:31:25.108Z","repository":{"id":321955020,"uuid":"1070887925","full_name":"chaddyc/pgbouncer","owner":"chaddyc","description":"PGBouncer production ready docker container","archived":false,"fork":false,"pushed_at":"2025-12-29T16:46:25.000Z","size":32,"stargazers_count":0,"open_issues_count":0,"forks_count":0,"subscribers_count":0,"default_branch":"main","last_synced_at":"2026-01-01T19:59:45.144Z","etag":null,"topics":["database","docker","kubernetes","pgbouncer","postgresql"],"latest_commit_sha":null,"homepage":"https://hub.docker.com/r/chaddyc/pgbouncer","language":"Shell","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/chaddyc.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":".github/CODEOWNERS","security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null,"zenodo":null,"notice":null,"maintainers":null,"copyright":null,"agents":null,"dco":null,"cla":null}},"created_at":"2025-10-06T15:11:16.000Z","updated_at":"2025-12-29T16:37:36.000Z","dependencies_parsed_at":null,"dependency_job_id":null,"html_url":"https://github.com/chaddyc/pgbouncer","commit_stats":null,"previous_names":["chaddyc/pgbouncer"],"tags_count":3,"template":false,"template_full_name":null,"purl":"pkg:github/chaddyc/pgbouncer","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/chaddyc%2Fpgbouncer","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/chaddyc%2Fpgbouncer/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/chaddyc%2Fpgbouncer/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/chaddyc%2Fpgbouncer/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/chaddyc","download_url":"https://codeload.github.com/chaddyc/pgbouncer/tar.gz/refs/heads/main","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/chaddyc%2Fpgbouncer/sbom","scorecard":null,"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":286080680,"owners_count":31500397,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2026-04-07T03:10:19.677Z","status":"ssl_error","status_checked_at":"2026-04-07T03:10:13.982Z","response_time":105,"last_error":"SSL_connect returned=1 errno=0 peeraddr=140.82.121.5:443 state=error: unexpected eof while reading","robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":false,"can_crawl_api":true,"host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["database","docker","kubernetes","pgbouncer","postgresql"],"created_at":"2025-12-29T18:26:57.012Z","updated_at":"2026-04-07T04:31:25.097Z","avatar_url":"https://github.com/chaddyc.png","language":"Shell","funding_links":[],"categories":[],"sub_categories":[],"readme":"# PgBouncer Docker Container\n\n![Docker](https://img.shields.io/badge/docker-%230db7ed.svg?style=for-the-badge\u0026logo=docker\u0026logoColor=white)\n![PostgreSQL](https://img.shields.io/badge/postgres-%23316192.svg?style=for-the-badge\u0026logo=postgresql\u0026logoColor=white)\n![Alpine Linux](https://img.shields.io/badge/Alpine_Linux-%230D597F.svg?style=for-the-badge\u0026logo=alpine-linux\u0026logoColor=white)\n![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg?style=for-the-badge)\n\n\nA production-ready, lightweight Docker container for [PgBouncer](https://www.pgbouncer.org/) - a lightweight connection pooler for PostgreSQL. Built on Alpine Linux with comprehensive configuration management through environment variables.\n\n## 🚀 Features\n\n- **Lightweight**: Based on Alpine Linux for minimal resource usage\n- **Environment-driven Configuration**: Complete configuration through environment variables\n- **Automatic Setup**: Auto-generates `pgbouncer.ini` and `userlist.txt` on startup\n- **Security-focused**: Scram-sha-256 password hashing, non-root execution, proper file permissions\n- **Production-ready**: Health checks, graceful shutdown, comprehensive logging\n- **Easy Deployment**: Docker Compose support with PostgreSQL integration\n- **Validation**: Configuration validation and database connectivity testing\n\n## 📋 Table of Contents\n\n- [Quick Start](#-quick-start)\n- [Configuration](#-configuration)\n- [Environment Variables](#-environment-variables)\n- [Deployment](#-deployment)\n- [Usage Examples](#-usage-examples)\n- [Monitoring](#-monitoring)\n- [Troubleshooting](#-troubleshooting)\n- [Contributing](#-contributing)\n- [License](#-license)\n\n## 🚀 Quick Start\n\n### Using Docker Compose (Recommended)\n\n1. **Clone the repository:**\n   ```bash\n   git clone \u003crepository-url\u003e\n   cd pgbouncer-docker\n   ```\n\n2. **Start the services:**\n   ```bash\n   docker-compose up -d\n   ```\n\n3. **Connect to PgBouncer:**\n   ```bash\n   psql -h localhost -p 6432 -U myuser -d myapp\n   ```\n\n### Using Docker\n\n```bash\n# Build the image\ndocker build -t my-pgbouncer .\n\n# Run the container\ndocker run -d \\\n  --name pgbouncer \\\n  -p 6432:6432 \\\n  -e DB_HOST=postgres-server \\\n  -e DB_PORT=5432 \\\n  -e DB_USER=myuser \\\n  -e DB_PASSWORD=mypassword \\\n  -e DB_NAME=myapp \\\n  my-pgbouncer\n```\n\n## ⚙️ Configuration\n\nThe container is configured entirely through environment variables. The entrypoint script automatically generates the PgBouncer configuration files on startup.\n\n### Required Environment Variables\n\n| Variable | Description | Example |\n|----------|-------------|---------|\n| `DB_HOST` | PostgreSQL server hostname | `postgres` |\n| `DB_PORT` | PostgreSQL server port | `5432` |\n| `DB_USER` | Database username | `myuser` |\n| `DB_PASSWORD` | Database password | `mypassword` |\n| `DB_NAME` | Database name | `myapp` |\n\n### Optional Configuration\n\n| Variable | Description | Default |\n|----------|-------------|---------|\n| `PGBOUNCER_PORT` | PgBouncer listen port | `6432` |\n| `PGBOUNCER_DATABASE` | Database pattern | `\"*\"` |\n| `PGBOUNCER_POOL_MODE` | Pool mode (transaction/session/statement) | `transaction` |\n| `PGBOUNCER_AUTH_TYPE` | Authentication type | `md5` |\n\n## 🔧 Environment Variables\n\n### Connection Pool Settings\n```bash\nPGBOUNCER_MAX_CLIENT_CONN=100          # Maximum client connections\nPGBOUNCER_DEFAULT_POOL_SIZE=20         # Default pool size per database\nPGBOUNCER_MIN_POOL_SIZE=5              # Minimum pool size\nPGBOUNCER_RESERVE_POOL_SIZE=5          # Reserved connections\nPGBOUNCER_MAX_DB_CONNECTIONS=50        # Maximum database connections\nPGBOUNCER_MAX_USER_CONNECTIONS=50      # Maximum connections per user\n```\n\n### Timeout Settings (in seconds)\n```bash\nPGBOUNCER_SERVER_LIFETIME=3600         # Connection lifetime\nPGBOUNCER_SERVER_IDLE_TIMEOUT=600      # Server idle timeout\nPGBOUNCER_CLIENT_IDLE_TIMEOUT=0        # Client idle timeout (0 = disabled)\n```\n\n### Logging Settings\n```bash\nPGBOUNCER_LOG_CONNECTIONS=1            # Log connections (0/1)\nPGBOUNCER_LOG_DISCONNECTIONS=1         # Log disconnections (0/1)\nPGBOUNCER_LOG_POOLER_ERRORS=1          # Log pooler errors (0/1)\nPGBOUNCER_STATS_PERIOD=60              # Stats logging period\n```\n\n### Performance Settings\n```bash\nPGBOUNCER_SERVER_RESET_QUERY=\"DISCARD ALL\"\nPGBOUNCER_IGNORE_STARTUP_PARAMETERS=\"extra_float_digits\"\n```\n\n### Admin Access\n```bash\nPGBOUNCER_ADMIN_USERS=myuser           # Users with admin access\nPGBOUNCER_STATS_USERS=myuser           # Users with stats access\n```\n\n## 🚢 Deployment\n\n### Docker Compose with PostgreSQL\n\n```yaml\nversion: '3.8'\n\nservices:\n  postgres:\n    image: postgres:18.0\n    environment:\n      POSTGRES_DB: myapp\n      POSTGRES_USER: myuser\n      POSTGRES_PASSWORD: mypassword\n    volumes:\n      - postgres_data:/var/lib/postgresql/18/docker\n    healthcheck:\n      test: [\"CMD-SHELL\", \"pg_isready -U myuser -d myapp\"]\n      interval: 10s\n      timeout: 5s\n      retries: 5\n\n  pgbouncer:\n    build: .\n    environment:\n      DB_HOST: postgres\n      DB_PORT: 5432\n      DB_USER: myuser\n      DB_PASSWORD: mypassword\n      DB_NAME: myapp\n      PGBOUNCER_POOL_MODE: transaction\n      PGBOUNCER_DEFAULT_POOL_SIZE: 20\n    ports:\n      - \"6432:6432\"\n    depends_on:\n      postgres:\n        condition: service_healthy\n    healthcheck:\n      test: [\"CMD-SHELL\", \"psql -h localhost -p 6432 -U myuser -d myapp -c 'SELECT 1;' || exit 1\"]\n      interval: 10s\n      timeout: 5s\n      retries: 5\n\nvolumes:\n  postgres_data:\n```\n\n### Kubernetes Deployment\n\n```yaml\napiVersion: apps/v1\nkind: Deployment\nmetadata:\n  name: pgbouncer\nspec:\n  replicas: 2\n  selector:\n    matchLabels:\n      app: pgbouncer\n  template:\n    metadata:\n      labels:\n        app: pgbouncer\n    spec:\n      containers:\n      - name: pgbouncer\n        image: my-pgbouncer:latest\n        ports:\n        - containerPort: 6432\n        env:\n        - name: DB_HOST\n          value: \"postgres-service\"\n        - name: DB_PORT\n          value: \"5432\"\n        - name: DB_USER\n          valueFrom:\n            secretKeyRef:\n              name: postgres-credentials\n              key: username\n        - name: DB_PASSWORD\n          valueFrom:\n            secretKeyRef:\n              name: postgres-credentials\n              key: password\n        - name: DB_NAME\n          value: \"myapp\"\n        livenessProbe:\n          exec:\n            command:\n            - psql\n            - -h\n            - localhost\n            - -p\n            - \"6432\"\n            - -U\n            - $(DB_USER)\n            - -d\n            - $(DB_NAME)\n            - -c\n            - \"SELECT 1;\"\n          initialDelaySeconds: 30\n          periodSeconds: 10\n        resources:\n          requests:\n            memory: \"64Mi\"\n            cpu: \"50m\"\n          limits:\n            memory: \"128Mi\"\n            cpu: \"100m\"\n---\napiVersion: v1\nkind: Service\nmetadata:\n  name: pgbouncer-service\nspec:\n  selector:\n    app: pgbouncer\n  ports:\n  - protocol: TCP\n    port: 6432\n    targetPort: 6432\n```\n\n## 📊 Usage Examples\n\n### Basic Connection\n\n```bash\n# Connect using psql\npsql -h localhost -p 6432 -U myuser -d myapp\n\n# Connection string\npostgresql://myuser:mypassword@localhost:6432/myapp\n```\n\n### Admin Commands\n\n```bash\n# Connect to PgBouncer admin console\npsql -h localhost -p 6432 -U myuser -d pgbouncer\n\n# Show active pools\nSHOW POOLS;\n\n# Show database configuration\nSHOW DATABASES;\n\n# Show connection statistics\nSHOW STATS;\n\n# Show current configuration\nSHOW CONFIG;\n\n# Reload configuration (after changes)\nRELOAD;\n\n# Pause all activity\nPAUSE;\n\n# Resume activity\nRESUME;\n```\n\n### Application Integration\n\n#### Python (psycopg2)\n```python\nimport psycopg2\n\nconn = psycopg2.connect(\n    host=\"pgbouncer-host\",\n    port=6432,\n    database=\"myapp\",\n    user=\"myuser\",\n    password=\"mypassword\"\n)\n```\n\n#### Node.js (pg)\n```javascript\nconst { Pool } = require('pg');\n\nconst pool = new Pool({\n  host: 'pgbouncer-host',\n  port: 6432,\n  database: 'myapp',\n  user: 'myuser',\n  password: 'mypassword',\n});\n```\n\n#### Go (lib/pq)\n```go\nimport (\n    \"database/sql\"\n    _ \"github.com/lib/pq\"\n)\n\ndb, err := sql.Open(\"postgres\", \n    \"host=pgbouncer-host port=6432 user=myuser password=mypassword dbname=myapp sslmode=disable\")\n```\n\n#### Java (JDBC)\n```java\nimport java.sql.Connection;\nimport java.sql.DriverManager;\nimport java.sql.SQLException;\n\npublic class DatabaseConnection {\n    private static final String URL = \"jdbc:postgresql://pgbouncer-host:6432/myapp\";\n    private static final String USER = \"myuser\";\n    private static final String PASSWORD = \"mypassword\";\n    \n    public static Connection getConnection() throws SQLException {\n        return DriverManager.getConnection(URL, USER, PASSWORD);\n    }\n    \n    // Using HikariCP connection pool (recommended)\n    public static HikariDataSource createDataSource() {\n        HikariConfig config = new HikariConfig();\n        config.setJdbcUrl(URL);\n        config.setUsername(USER);\n        config.setPassword(PASSWORD);\n        config.setMaximumPoolSize(20);\n        return new HikariDataSource(config);\n    }\n}\n```\n\n#### C# (Npgsql)\n```csharp\nusing Npgsql;\nusing Microsoft.Extensions.DependencyInjection;\n\n// Basic connection\nvar connectionString = \"Host=pgbouncer-host;Port=6432;Database=myapp;Username=myuser;Password=mypassword\";\n\nusing var connection = new NpgsqlConnection(connectionString);\nawait connection.OpenAsync();\n\n// ASP.NET Core DI registration\nservices.AddDbContext\u003cApplicationDbContext\u003e(options =\u003e\n    options.UseNpgsql(\"Host=pgbouncer-host;Port=6432;Database=myapp;Username=myuser;Password=mypassword\"));\n\n// Connection pooling with NpgsqlDataSource (.NET 6+)\nvar dataSourceBuilder = new NpgsqlDataSourceBuilder(connectionString);\ndataSourceBuilder.UseLoggerFactory(loggerFactory);\nawait using var dataSource = dataSourceBuilder.Build();\nawait using var connection = await dataSource.OpenConnectionAsync();\n```\n\n## 📈 Monitoring\n\n### Health Checks\n\nThe container includes built-in health checks:\n\n```bash\n# Check container health\ndocker ps\n\n# View health check logs\ndocker inspect pgbouncer | jq '.[0].State.Health'\n```\n\n### Log Files\n\n```bash\n# View PgBouncer logs\ndocker logs pgbouncer\n\n# View logs inside container\ndocker exec pgbouncer tail -f /var/log/pgbouncer/pgbouncer.log\n```\n\n### Statistics Monitoring\n\n```sql\n-- Connect to pgbouncer admin\npsql -h localhost -p 6432 -U myuser -d pgbouncer\n\n-- Pool statistics\nSHOW STATS;\n\n-- Pool status\nSHOW POOLS;\n\n-- Active clients\nSHOW CLIENTS;\n\n-- Active servers\nSHOW SERVERS;\n```\n\n### Prometheus Metrics\n\nFor Prometheus monitoring, consider using [pgbouncer_exporter](https://github.com/prometheus-community/pgbouncer_exporter):\n\n```yaml\nversion: '3.8'\n\nservices:\n  # ... pgbouncer service ...\n  \n  pgbouncer-exporter:\n    image: prometheuscommunity/pgbouncer-exporter:latest\n    environment:\n      PGBOUNCER_EXPORTER_HOST: pgbouncer\n      PGBOUNCER_EXPORTER_PORT: 6432\n      PGBOUNCER_EXPORTER_USER: myuser\n      PGBOUNCER_EXPORTER_PASSWORD: mypassword\n    ports:\n      - \"9127:9127\"\n```\n\n## 🔧 Troubleshooting\n\n### Common Issues\n\n#### 1. Database Connection Failures\n```bash\n# Check database connectivity\ndocker exec pgbouncer psql -h $DB_HOST -p $DB_PORT -U $DB_USER -d $DB_NAME -c \"SELECT 1;\"\n\n# Check environment variables\ndocker exec pgbouncer env | grep -E \"^(DB_|PGBOUNCER_)\"\n```\n\n#### 2. Authentication Errors\n```bash\n# Verify userlist.txt generation\ndocker exec pgbouncer cat /etc/pgbouncer/userlist.txt\n\n# Check MD5 hash generation\ndocker exec pgbouncer sh -c 'echo -n \"${DB_PASSWORD}${DB_USER}\" | md5sum'\n```\n\n#### 3. Pool Exhaustion\n```sql\n-- Check pool utilization\nSHOW POOLS;\nSHOW STATS;\n\n-- Increase pool sizes if needed\n```\n\n#### 4. Configuration Issues\n```bash\n# View generated configuration\ndocker exec pgbouncer cat /etc/pgbouncer/pgbouncer.ini\n\n# Test configuration syntax\ndocker exec pgbouncer pgbouncer -v /etc/pgbouncer/pgbouncer.ini\n```\n\n### Debug Mode\n\nEnable verbose logging for troubleshooting:\n\n```bash\n# Add to environment variables\nPGBOUNCER_VERBOSE=2\nPGBOUNCER_LOG_CONNECTIONS=1\nPGBOUNCER_LOG_DISCONNECTIONS=1\nPGBOUNCER_LOG_POOLER_ERRORS=1\n```\n\n### Performance Tuning\n\n#### Pool Mode Selection\n- **Transaction**: Best for most applications (recommended)\n- **Session**: Use only if your app requires session state\n- **Statement**: Highest throughput but limited compatibility\n\n#### Pool Sizing Guidelines\n- Start with `default_pool_size = 20-25`\n- Set `max_client_conn` higher than expected concurrent users\n- Monitor pool utilization: `cl_active / cl_waiting` ratio\n- Adjust based on your application's connection patterns\n\n#### Timeout Tuning\n- `server_lifetime`: Set to handle connection rotation (3600s default)\n- `server_idle_timeout`: Adjust based on database timeout settings\n- `client_idle_timeout`: Set to 0 for most applications\n\n## 🤝 Contributing\n\nContributions are welcome! Please feel free to submit a Pull Request.\n\n### Development Setup\n\n1. Fork the repository\n2. Create a feature branch: `git checkout -b feature-name`\n3. Make your changes\n4. Test the changes: `docker-compose up --build`\n5. Submit a pull request\n\n### Reporting Issues\n\nPlease include:\n- Docker version\n- Container logs\n- Environment variables (without sensitive data)\n- Steps to reproduce\n\n## 📄 License\n\nThis project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details.\n\n## 🔗 References\n\n- [PgBouncer Official Documentation](https://www.pgbouncer.org/)\n- [PostgreSQL Documentation](https://www.postgresql.org/docs/)\n- [Docker Best Practices](https://docs.docker.com/develop/best-practices/)\n\n## ⭐ Support\n\nIf this project helped you, please consider giving it a ⭐ on GitHub!\n\n---\n\n**Made with ❤️ for the PostgreSQL community**\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fchaddyc%2Fpgbouncer","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fchaddyc%2Fpgbouncer","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fchaddyc%2Fpgbouncer/lists"}