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
Note that, in windows, the pgpass.conf
file must be in the following folder:
%APPDATA%\postgresql\pgpass.conf
if there's no postgresql
folder inside the %APPDATA%
folder, create it.
the pgpass.conf
file content is something like:
localhost:5432:dbname:dbusername:dbpassword
cheers
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
Or you can set up crontab to run a script. Inside that script you can set an environment variable like this:
export PGPASSWORD="$put_here_the_password"
This way if you have multiple commands that would require password you can put them all in the script. If the password changes you only have to change it in one place (the script).
And I agree with Joshua, using pg_dump -Fc
generates the most flexible export format and is already compressed. For more info see: pg_dump documentation
E.g.
# dump the database in custom-format archive
pg_dump -Fc mydb > db.dump
# restore the database
pg_restore -d newdb db.dump
@Josue Alexander Ibarra answer works on centos 7 and version 9.5 if --dbname is not passed.
pg_dump postgresql://username:password@127.0.0.1:5432/mydatabase
You just need to open pg_hba.conf and sets trust in all methods. That's works for me. Therefore the security is null.
As detailed in this blog post , there are two ways to non interactively provide a password to PostgreSQL utilities such as the "pg_dump" command: using the ".pgpass" file or using the "PGPASSWORD" environment variable.