How to pass in password to pg_dump?

后端 未结 16 882
深忆病人
深忆病人 2020-11-28 00:58

I\'m trying to create a cronjob to back up my database every night before something catastrophic happens. It looks like this command should meet my needs:

0          


        
16条回答
  •  北荒
    北荒 (楼主)
    2020-11-28 01:21

    For a one-liner, like migrating a database you can use --dbname followed by a connection string (including the password) as stated in the pg_dump manual

    In essence.

    pg_dump --dbname=postgresql://username:password@127.0.0.1:5432/mydatabase

    Note: Make sure that you use the option --dbname instead of the shorter -d and use a valid URI prefix, postgresql:// or postgres://.

    The general URI form is:

    postgresql://[user[:password]@][netloc][:port][/dbname][?param1=value1&...]

    Best practice in your case (repetitive task in cron) this shouldn't be done because of security issues. If it weren't for .pgpass file I would save the connection string as an environment variable.

    export MYDB=postgresql://username:password@127.0.0.1:5432/mydatabase

    then have in your crontab

    0 3 * * * pg_dump --dbname=$MYDB | gzip > ~/backup/db/$(date +%Y-%m-%d).psql.gz

提交回复
热议问题