85
58

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

PostgreSQL コンテナの backup / restore をする

Posted at

Docker コンテナとして動いている PostgreSQL からデータを backup する、またデータを restore する(PostgreSQL コンテナにデータを注入する)方法です。
ここで使っているイメージは Docker Hub 公式の postgres イメージです。今回は postgres:9.4.1 を使いました。

$ docker run -d -p 5432:5432 --name postgres postgres:9.4.1

backup する

$ docker exec [container_id or name] pg_dumpall -U postgres > dump.sql

コンテナ内のデータベース全体が SQL として dump されます。

dump.sql
--
-- PostgreSQL database cluster dump
--

SET default_transaction_read_only = off;

SET client_encoding = 'UTF8';
SET standard_conforming_strings = on;

--
-- Roles
--

CREATE ROLE postgres;
ALTER ROLE postgres WITH SUPERUSER INHERIT CREATEROLE CREATEDB LOGIN REPLICATION;

...

restore する

他の PostgreSQL(コンテナに限らず)から取得した dump.sql が必要です。

$ cat dump.sql | docker exec -i [container_id or name] psql -U postgres
SET
SET
SET
ERROR:  role "postgres" already exists
ALTER ROLE
REVOKE
REVOKE
GRANT
GRANT
You are now connected to database "postgres" as user "postgres".
SET
SET
SET
SET
SET
SET
SET
...

ちゃんとデータが流し込まれたか確認

$ docker exec -it postgres psql -U postgres
psql (9.4.1)
Type "help" for help.

postgres=# \d
                  List of relations
 Schema |         Name         |   Type   |  Owner
--------+----------------------+----------+----------
 public | ramesh_images        | table    | postgres
 public | ramesh_images_id_seq | sequence | postgres
 public | schema_migrations    | table    | postgres
(3 rows)

postgres=#

:tada:

85
58
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
85
58

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?