Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

pg_restore to postgres running in docker container

I have a backup of a database that I would to restore to a postgres database running inside a docker container.

I'm using docker-machine on OS X.
Postgres image is postgres:9.4.

This is the script I've come up with so far:

pg_restore --verbose --clean --no-acl --no-owner \
  -h tcp://`docker-machine ip default`:5432 \
  -U postgres \
  -d tonsser-api_development latest.dump

But that doesn't work. I get the error:

pg_restore: connecting to database for restore
pg_restore: [archiver (db)] connection to database "tonsser-api_development" failed: could not translate host name "tcp://192.168.99.100:5432" to address: nodename nor servname provided, or not known
like image 656
David Pedersen Avatar asked Nov 30 '15 10:11

David Pedersen


People also ask

How do I connect to a PostgreSQL container?

Connecting to the PSQL server via CLI : Run the below command to enter into the container (with the ID from step-1). docker exec -it <PSQL-Container-ID> bash. Authenticate to start using as postgres user. psql -h localhost -p 5432 -U postgres -W.


2 Answers

There seems to be no proper solution to do this on runtime, however copying the dumpfile to the container:

docker cp dumpfile DBcontainer:/dumpfile

and restore from within the container:

docker  exec -i -t DBcontainer /bin/bash
psql DBname < dumpfile

worked well for a one time use...

like image 89
nyx00 Avatar answered Oct 19 '22 17:10

nyx00


You have to use a connection string, e.g. $DATABASE_URL

The following works well for me:

docker-compose exec fooapp pg_restore 
  --verbose --clean --no-acl --no-owner 
  -d $DATABASE_URL foo.dump

For extra points, you can create a rake task (assuming you're using a Rails app), as follows:

namespace :db do
  desc 'Import a given file into the database'
  task :import, [:path] => :environment do |_t, args|
    dump_path = args.path
    system 'pg_restore --verbose --clean --no-acl --no-owner -d $DATABASE_URL '\
    + dump_path
  end
end

Put that file in lib/tasks, then you can call something like:

docker-compose exec fooapp bundle exec rails db:import[foo.dump]
like image 1
Caleb Avatar answered Oct 19 '22 17:10

Caleb