3.6 KiB
Berikut cara install PgBouncer di Ubuntu (termasuk Ubuntu Server 24.04/26.04).
1. Install
Update package:
sudo apt update
Install PgBouncer:
sudo apt install pgbouncer
Cek versi:
pgbouncer -V
Contoh output:
PgBouncer 1.22.x
2. File konfigurasi
Biasanya berada di:
/etc/pgbouncer/
Lihat isinya:
ls /etc/pgbouncer
Biasanya terdapat:
pgbouncer.ini
userlist.txt
3. Konfigurasi pgbouncer.ini
Edit:
sudo nano /etc/pgbouncer/pgbouncer.ini
Contoh konfigurasi:
[databases]
mydb = host=127.0.0.1 port=5432 dbname=mydb
[pgbouncer]
listen_addr = 0.0.0.0
listen_port = 6432
auth_type = md5
auth_file = /etc/pgbouncer/userlist.txt
pool_mode = transaction
max_client_conn = 1000
default_pool_size = 50
min_pool_size = 10
reserve_pool_size = 10
ignore_startup_parameters = extra_float_digits
server_reset_query = DISCARD ALL
log_connections = 1
log_disconnections = 1
4. Membuat password MD5
PgBouncer dengan auth_type = md5 membutuhkan password dalam format khusus.
Misalnya:
User:
postgres
Password:
admin123
Hitung hash:
echo -n "admin123postgres" | md5sum
Hasil misalnya:
6b0f9e0d9a5f8f4c....
Masukkan ke userlist.txt:
sudo nano /etc/pgbouncer/userlist.txt
Isi:
"postgres" "md56b0f9e0d9a5f8f4c..."
Perhatikan formatnya:
md5 + md5(password + username)
5. Restart service
sudo systemctl restart pgbouncer
Cek status:
sudo systemctl status pgbouncer
Enable saat boot:
sudo systemctl enable pgbouncer
6. Cek port
sudo ss -ltnp | grep 6432
Harus muncul:
LISTEN 0 128 0.0.0.0:6432
7. Test koneksi
Gunakan psql:
psql -h localhost -p 6432 -U postgres mydb
Kalau berhasil berarti PgBouncer sudah aktif.
8. Ubah aplikasi Go
Sebelumnya:
postgres://postgres:password@localhost:5432/mydb
Menjadi:
postgres://postgres:password@localhost:6432/mydb
Hanya port yang berubah.
9. Monitoring PgBouncer
Masuk ke database virtual pgbouncer:
psql -h localhost -p 6432 -U postgres pgbouncer
Lihat pool:
SHOW POOLS;
Lihat client:
SHOW CLIENTS;
Lihat server:
SHOW SERVERS;
Lihat statistik:
SHOW STATS;
10. Setting PostgreSQL
Jika memakai PgBouncer, biasanya max_connections di PostgreSQL tidak perlu terlalu besar.
Contoh:
max_connections = 100
Sedangkan PgBouncer:
default_pool_size = 50
max_client_conn = 1000
Artinya:
1000 Client
│
▼
PgBouncer
│
50 koneksi aktif
│
PostgreSQL
Rekomendasi untuk aplikasi Go
Karena Anda sedang mengembangkan backend Go dengan database/sql, konfigurasi berikut umumnya cocok:
PostgreSQL
max_connections = 100
PgBouncer
pool_mode = transaction
default_pool_size = 30
max_client_conn = 1000
Go (database/sql)
db.SetMaxOpenConns(10)
db.SetMaxIdleConns(5)
db.SetConnMaxLifetime(30 * time.Minute)
db.SetConnMaxIdleTime(10 * time.Minute)
dsn := "postgres://postgres:admin123@192.168.1.10:6432/koperasi?sslmode=disable"
Konekkan keport PgBouncer
Konfigurasi ini biasanya mampu menangani beban yang jauh lebih tinggi dibandingkan aplikasi yang terhubung langsung ke PostgreSQL, sambil menjaga jumlah koneksi database tetap efisien.