## イメージ
公式イメージを使う。
<div class="link-card-v2">
<div class="link-card-v2-site">
<img class="link-card-v2-site-icon" src="https://hub.docker.com/favicon.ico" />
<span class="link-card-v2-site-name">hub.docker.com</span>
</div>
<div class="link-card-v2-title">
https://hub.docker.com/_/postgres
</div>
<a href="https://hub.docker.com/_/postgres"></a>
</div>
## 環境
| 対象 | バージョン |
| ---------- | ------------------------ |
| [[Docker]] | 27.5.0, build a187fa5 |
| [[Ubuntu]] | 24.04.1 LTS (in [[WSL]]) |
## 設定ファイル
[[PostgreSQL]]のバージョンは17系。
`docker-compose.yml`
```yaml
services:
db:
image: postgres:17
container_name: postgres-sample
ports:
- 15432:5432
volumes:
- ./docker-entrypoint-initdb.d:/docker-entrypoint-initdb.d
environment:
POSTGRES_PASSWORD: password
```
## 初期化ファイル
`docker-entrypoint-initdb.d/init.sql`
```sql
-- dockerを経由せずアクセスするためにパスワードを設定
CREATE USER user2 WITH PASSWORD 'password';
CREATE DATABASE mydb;
\c mydb;
ALTER DEFAULT PRIVILEGES IN SCHEMA public GRANT ALL ON TABLES TO user2;
CREATE TYPE options AS ENUM ('option1', 'option2', 'option3');
CREATE TABLE types (
int INT PRIMARY KEY,
varchar VARCHAR(255) NOT NULL,
date DATE,
time TIME,
datetime TIMESTAMP,
timestamp TIMESTAMP,
enum OPTIONS,
bool BOOLEAN
);
INSERT INTO types VALUES
(
1,
'one',
'2024-11-26',
'11:22:33',
'2024-11-26 00:03:00',
'2024-11-26 00:03:01',
'option1',
true
),
(
2,
'two',
NULL,
NULL,
NULL,
NULL,
NULL,
NULL
);
CREATE TABLE pets (
"id" VARCHAR(32) PRIMARY KEY,
"name" VARCHAR(255) NOT NULL,
"stay" BOOLEAN NOT NULL,
"price" INT,
"joined_year" SMALLINT NOT NULL,
"created_at" TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
"updated_at" TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP
);
INSERT INTO pets
("id", "name", "stay", "price", "joined_year")
VALUES
('tatsuwo', 'タツヲ', true, 9000, 2009),
('seikichi', 'セイキチ', true, 5000, 2007),
('masaharu', 'マサハル', true, 42000, 2021),
('mitarashi', 'みたらし', true, 44000, 2021),
('wanbe', 'わんべえ', true, 3000, 2010),
('hyosuke', 'ヒョウスケ', true, NULL, 2014),
('raizo', 'ライゾウ', true, NULL, 2014),
('robao', 'ロバオ', false, NULL, 1987),
('mimizo', 'みみぞう', false, NULL, 2004),
('mimiko', 'みみこ', false, NULL, 2006),
('momochi', 'ももち', false, NULL, 2019);
```
## コマンド
### 起動
```console
docker compose up -d
```
### 接続確認
```console
docker exec -it postgres-sample psql --username user2 mydb
```
[[データベースクライアント]]が起動したら[[SQL]]を実行。
```sql
select * from pets;
```
結果が出ればOK。