Running PostGraphile in Docker
This guide has been updated for PostGraphile V5, but has not yet been tested. Exercise caution, and please report any issues.
本指南已针对 PostGraphile V5 进行了更新,但尚未经过实际测试。使用时请谨慎,若遇到任何问题欢迎向我们反馈。
The following guide describes how to run a network of Docker containers on a local machine, including one container for a PostgreSQL database and one container for PostGraphile. A the end of this guide, you will have a GraphQL API exposing data from a PostgreSQL database, both running locally on your machine in separate Docker containers. It has been developed and tested on:
本指南介绍如何在本地机器上运行一组相互连通的 Docker 容器,包括一个 PostgreSQL 数据库容器和一个 PostGraphile 容器。完成本指南后,你将在本地拥有一个对外暴露 PostgreSQL 数据的 GraphQL API,两者分别运行在独立的 Docker 容器中。本方案已在以下操作系统上完成开发与测试:
-
Linux
Linux
-
Windows Pro
Windows 专业版
-
Windows Home
Windows 家庭版
Requirements环境要求
This requires to have Docker and Docker Compose installed on your workstation. If you are new to Docker and need to install it, you can refer to their official documentation or follow the steps below.
开始之前,你的开发机上需要安装好 Docker 和 Docker Compose。如果你刚接触 Docker 尚未安装,可以参考其官方文档,或按以下步骤进行安装。
If you use Docker Desktop for Windows, it comes automatically with Docker Compose.
如果你使用的是 Docker Desktop for Windows,安装包中已自带 Docker Compose。
Install Docker and Docker Compose on Linux在 Linux 上安装 Docker 和 Docker Compose
Docker安装 Docker
Add the Docker repository to your Linux repository. Execute the following commands in a terminal window.
将 Docker 软件源添加到你的 Linux 仓库列表中。请在终端窗口执行以下命令:
sudo apt-get update
sudo apt-get install apt-transport-https ca-certificates curl software-properties-common
curl -fsSL https://download.docker.com/linux/ubuntu/gpg | sudo apt-key add -
sudo add-apt-repository "deb [arch=amd64] https://download.docker.com/linux/ubuntu $(lsb_release -cs) stable"
Install Docker Community Edition.
安装 Docker 社区版(Docker CE):
sudo apt-get update
sudo apt-get install docker-ce
Add your user to the docker group to setup its permissions. Make sure to restart your machine after executing this command.
将当前用户添加到 docker 用户组以配置操作权限。执行此命令后请务必重启电脑。
sudo usermod -a -G docker <username>
Test your Docker installation. Executing the following command will
automatically download the hello-world Docker image if it does not exist and
run it.
测试 Docker 是否安装成功。执行以下命令时,如果本地尚不存在 hello-world Docker 镜像,Docker 会自动下载并运行它:
docker run hello-world
Remove the hello-world image once you're done.
测试完成后,删除 hello-world 镜像:
docker image ls
docker rmi -f hello-world
Docker Compose安装 Docker Compose
Docker Compose helps you to run a network of several containers at once thanks to configuration files instead of providing all arguments in the command line interface. It makes it easier to manage your containers as command lines can become very long and unreadable due to the high number of arguments. Execute the following command in a terminal window.
Docker Compose 允许你通过配置文件一次性编排并运行多个容器组成的网络,而无需在命令行中手动传入所有参数。当参数数量较多时,命令行会变得冗长且难以维护,而使用配置文件则能让容器管理轻松得多。请在终端窗口执行以下命令:
sudo apt install docker-compose
Install Docker on Windows Pro在 Windows 专业版上安装 Docker
Docker Desktop for Windows安装 Docker Desktop for Windows
Install Docker Community Edition for Windows from the following the URL: Docker Desktop for Windows. Just follow the default installation settings. It comes automatically with Docker Compose.
从以下地址下载并安装适用于 Windows 的 Docker 社区版:Docker Desktop for Windows。按默认设置完成安装即可,其中已自动包含 Docker Compose。
Install Docker on Windows Home在 Windows 家庭版上安装 Docker
Docker Toolbox for Windows安装 Docker Toolbox for Windows
Install Docker Toolbox for Windows from the following the URL: Docker Toolbox for Windows. Just follow the default installation settings. It comes automatically with Docker Compose.
从以下地址下载并安装适用于 Windows 的 Docker Toolbox:Docker Toolbox for Windows。按默认设置完成安装即可,其中已自动包含 Docker Compose。
Create PostgreSQL Container创建 PostgreSQL 容器
Setup Environment Variables配置环境变量
Create a new file .env at the root of the repository with the content below.
This file will be used by Docker to load configuration parameters into
environment variables. In particular:
在仓库根目录下新建一个 .env 文件,填入以下内容。Docker 会读取该文件并将其中的配置参数加载为环境变量,具体包括:
-
POSTGRES_DB: name of the database to be created in the PostgreSQL container.POSTGRES_DB:要在 PostgreSQL 容器中创建的数据库名称。 -
POSTGRES_USER: default admin user created upon database initialization.POSTGRES_USER:数据库初始化时创建的默认管理员用户名。 -
POSTGRES_PASSWORD: password of the default admin user.POSTGRES_PASSWORD:默认管理员用户的密码。
# DB
# Parameters used by db container
POSTGRES_DB=forum_example
POSTGRES_USER=postgres
POSTGRES_PASSWORD=change_me
A better way to manager the database password would be to use Docker Secrets.
更好的数据库密码管理方式是使用 Docker Secrets。
Create Database Initialization Files创建数据库初始化文件
Create a new folder db at the root of the repository. It will be used to store
the files necessary to create the PostgreSQL container. In the db folder,
create a new subfolder init which will contain the SQL files used to
initialize the PostgreSQL database. Files located in the init folder will be
executed in sequence order when PostgreSQL initialize the database.
在仓库根目录下新建一个 db 文件夹,用于存放创建 PostgreSQL 容器所需的文件。然后在 db 文件夹中再创建一个 init 子文件夹,用来放置初始化 PostgreSQL 数据库的 SQL 脚本。PostgreSQL 在初始化数据库时,会按文件名顺序依次执行 init 文件夹中的脚本。
In this guide we will use a simple forum example. The database will contain two
tables: user and post. There is a relationship between user and post as
one user can have one or several posts. It is a "one-to-many" relationship (one
parent, many children). The author_id column in the post will be used as a
foreign key of the user table.
本指南以一个简单的论坛示例进行演示。数据库中包含两张表:user 和 post。两者之间存在关联关系:一个用户可以发表一篇或多篇帖子,即典型的“一对多”关系(一个父记录对应多个子记录)。post 表中的 author_id 列将作为外键关联到 user 表。
Create a first file 00-database.sql containing the database schema definition
as below.
首先创建 00-database.sql 文件,写入如下数据库 schema 定义:
\connect forum_example;
/*Create user table in public schema*/
CREATE TABLE public.user (
id SERIAL PRIMARY KEY,
username TEXT,
created_date TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
COMMENT ON TABLE public.user IS
'Forum users.';
/*Create post table in public schema*/
CREATE TABLE public.post (
id SERIAL PRIMARY KEY,
title TEXT,
body TEXT,
created_date TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
author_id INTEGER NOT NULL REFERENCES public.user(id)
);
COMMENT ON TABLE public.post IS
'Forum posts written by a user.';
For the sake of the example, we will also create a second file 01-data.sql to
populate the database with some dummy data.
为了方便演示,我们再创建第二个文件 01-data.sql,向数据库中填充一些测试数据:
\connect forum_example;
/*Create some dummy users*/
insert into public.user (username) values
('Benjie'),
('Singingwolfboy'),
('Lexius');
/*Create some dummy posts*/
insert into public.post (title, body, author_id) values
('First post example', 'Lorem ipsum dolor sit amet', 1),
('Second post example', 'Consectetur adipiscing elit', 2),
('Third post example', 'Aenean blandit felis sodales', 3);
Create PostgreSQL Dockerfile创建 PostgreSQL Dockerfile
The Dockerfile is used by Docker as a blueprint to build Docker images. Docker
containers are later on created based on these Docker images. More information
is available on the official
Postgres Docker Images but the standard
Dockerfile for PostgreSQL is extremely simple. In the folder db (not in the
folder init), create a new file named Dockerfile with the following content.
Docker 使用 Dockerfile 作为蓝图来构建 Docker 镜像,之后再基于这些镜像创建容器。关于镜像的更多信息可查阅官方 Postgres Docker Images 文档,但标准的 PostgreSQL Dockerfile 其实非常简单。在 db 文件夹下(注意不要放在 init 子文件夹中)新建一个名为 Dockerfile 的文件,内容如下:
FROM postgres:14-alpine
COPY ./init/ /docker-entrypoint-initdb.d/
The first line FROM postgres:14-alpine indicates to build the Docker image based
on the official PostgreSQL Docker image running in an Alpine Linux container.
The second line COPY ./init/ /docker-entrypoint-initdb.d/ will copy the
database initialization files (SQL) into the folder docker-entrypoint-initdb.d
located in the Docker container. This folder is read by PostgreSQL upon database
initialization and all its content is executed.
第一行 FROM postgres:14-alpine 表示基于运行在 Alpine Linux 容器中的官方 PostgreSQL 镜像进行构建。第二行 COPY ./init/ /docker-entrypoint-initdb.d/ 会将数据库初始化 SQL 文件复制到容器内的 docker-entrypoint-initdb.d 目录中——PostgreSQL 在首次初始化数据库时会自动读取该目录并执行其中的所有脚本。
Create Docker Compose File创建 Docker Compose 文件
Docker command lines can be verbose with a lot of parameters so we will use
Docker Compose to orchestrate the execution of our containers. Create a new file
docker-compose.yml at the root of the repository with the following content.
由于直接执行 Docker 命令需要传递大量繁琐参数,我们将使用 Docker Compose 来统一编排容器的运行。在仓库根目录下新建一个 docker-compose.yml 文件,内容如下:
version: "3.3"
services:
db:
container_name: forum-example-db
restart: always
image: forum-example-db
build:
context: ./db
volumes:
- db:/var/lib/postgresql/data
env_file:
- ./.env
networks:
- network
ports:
- 5432:5432
networks:
network:
volumes:
db:
Parameters description参数说明
| Parameter参数 | Description说明 |
|---|---|
| dbdb(服务键名) | Names of the services run by Docker Compose.Docker Compose 运行的服务名称。 |
| container_namecontainer_name(容器名称) | Guess what? It's the container name!顾名思义,就是容器的名称! |
| imageimage(镜像) | Name of the image to use to run the container.运行容器所使用的镜像名称。 |
| buildbuild(构建配置) | When a build context is provided, Docker Compose will build a custom image using the Dockerfile located in the context folder.当提供构建上下文时,Docker Compose 会使用上下文目录中的 Dockerfile 构建自定义镜像。 |
| contextcontext(构建上下文) | Indicates the folder where to find the Dockerfile to build the image.指定用于构建镜像的 Dockerfile 所在目录。 |
| volumesvolumes(数据卷) | Mapping between the Docker volume and the PostgreSQL folder in your container, in format docker_volume:container_folder. All the files generated in the container_folder will be copied in the docker_volume so that you can preserve and retrieve your data when stopping/restarting the container. The Docker volume is automatically created when running the db container for the first time.Docker 卷与容器内 PostgreSQL 数据目录之间的映射,格式为 docker_volume:container_folder。container_folder 中生成的所有文件都会同步保存在 docker_volume 中,这样在停止或重启容器时也能保留并恢复数据。首次运行 db 容器时,Docker 会自动创建该卷。 |
| env_fileenv_file(环境变量文件) | Path to the configuration file containing environment variables for the container. See Setup Environment Variables above.包含容器环境变量的配置文件路径。详见上文的配置环境变量。 |
| networksnetworks(网络配置) | Networks are used to group and connect containers as part of a same network.用于将多个容器划分到同一网络中以便彼此通信。 |
| portsports(端口映射) | Port, mapping between the port of your host machine and the port of your container, in format host_port:container_port指定宿主机端口与容器端口之间的映射关系,格式为 host_port:container_port。 |
| commandcommand(启动命令) | Command to be executed after the container starts. Each argument must be provided in a separate list item.容器启动后执行的命令。每个参数必须作为单独的列表项提供。 |
At this stage, the repository should look like this:
此时,代码仓库的目录结构应如下所示:
/
├─ db/
| ├─ init/
| | ├─ 00-database.sql
| | └─ 01-data.sql
| └─ Dockerfile
├─ .env
└─ docker-compose.yml
Create PostGraphile Container创建 PostGraphile 容器
Update Environment Variables更新环境变量
Update the file .env to add the DATABASE_URL which will be used by
PostGraphile to connect to the PostgreSQL database.
更新 .env 文件,添加 PostGraphile 用于连接 PostgreSQL 数据库的 DATABASE_URL:
[...]
# GRAPHQL
# Parameters used by graphql container
DATABASE_URL=postgres://postgres:change_me@db:5432/forum_example
The DATABASE_URL follows the syntax
postgres://<user>:<password>@db:5432/<db_name>.
DATABASE_URL 遵循 postgres://<user>:<password>@db:5432/<db_name> 的格式。
Create PostGraphile Dockerfile创建 PostGraphile Dockerfile
Create a new folder graphql at the root of the repository. It will be used to
store the files necessary to create the PostGraphile container.
在仓库根目录下新建一个 graphql 文件夹,用于存放创建 PostGraphile 容器所需的文件。
In graphql, create a package.json and lockfile (for example
package-lock.json) that install PostGraphile, then add a graphile.config.ts
to configure it.
在 graphql 文件夹中创建一个 package.json 及对应的锁文件(例如 package-lock.json)来安装 PostGraphile,然后添加 graphile.config.ts 进行配置:
{
"name": "postgraphile-docker",
"private": true,
"type": "module",
"dependencies": {
"postgraphile": "^5.0.0"
}
}
import { PostGraphileAmberPreset } from "postgraphile/presets/amber";
import { makePgService } from "postgraphile/adaptors/pg";
export default {
extends: [PostGraphileAmberPreset],
pgServices: [makePgService({ connectionString: process.env.DATABASE_URL })],
grafserv: {
host: "0.0.0.0",
port: 5678,
},
};
Create a new file Dockerfile in the graphql folder with the following
content.
在 graphql 文件夹下新建一个 Dockerfile 文件,内容如下:
FROM node:24-alpine
LABEL description="Instant high-performance GraphQL API for your PostgreSQL database https://github.com/graphile/postgraphile"
# Set app folder
WORKDIR /app
# Install dependencies
COPY package.json package-lock.json ./
RUN npm install
# Copy config and plugins
COPY graphile.config.ts ./
COPY plugins ./plugins
EXPOSE 5678
ENTRYPOINT ["npx", "--no-install", "postgraphile"]
Update Docker Compose File更新 Docker Compose 文件
Update the file docker-compose.yml under the services section to include the
GraphQL service.
更新 docker-compose.yml 文件,在 services 部分加入 GraphQL 服务配置:
version: "3.3"
services:
db: [...]
graphql:
container_name: forum-example-graphql
restart: always
image: forum-example-graphql
build:
context: ./graphql
env_file:
- ./.env
depends_on:
- db
networks:
- network
ports:
- 5678:5678
[...]
At this stage, the repository should look like this:
此时,代码仓库的目录结构应如下所示:
/
├─ db/
| ├─ init/
| | ├─ 00-database.sql
| | └─ 01-data.sql
| └─ Dockerfile
├─ graphql/
| ├─ graphile.config.ts
| ├─ package.json
| ├─ package-lock.json
| ├─ plugins/
| └─ Dockerfile
├─ .env
└─ docker-compose.yml
Build Images And Run Containers构建镜像并运行容器
Build Images构建镜像
You can build the Docker images by executing the following command from the root of the repository.
在仓库根目录下执行以下命令即可构建 Docker 镜像:
# Build images for all services in docker-compose.yml
docker-compose build
# You can also build images one by one
# For instance you can build the database image like this
docker-compose build db
# And build the graphql image like this
docker-compose build graphql
Run Containers运行容器
You can run the Docker containers by executing the following command from the root of the repository.
在仓库根目录下执行以下命令即可运行 Docker 容器:
When running the database container for the first time, Docker will
automatically create a Docker Volume to persist the data from the database.
The Docker Volume is automatically named as <your_repository_name>_db.
首次启动数据库容器时,Docker 会自动创建一个 Docker 卷(Docker Volume)用于持久化数据库数据,该卷会自动命名为 <your_repository_name>_db。
# Run containers for all services in docker-compose.yml
docker-compose up
# Run containers as daemon (in background)
docker-compose up -d
# Run only the database container as daemon
docker-compose up -d db
# Run only the GraphQL container as daemon
docker-compose up -d graphql
Each container can be accessed at the following addresses:
各个容器可通过以下地址访问:
| Container容器 | Docker on Linux / Windows ProLinux / Windows 专业版上的 Docker | Docker on Windows HomeWindows 家庭版上的 Docker |
|---|---|---|
| GraphQL API DocumentationGraphQL API 文档 | http://localhost:5678/graphiql | http://your_docker_machine_ip:5678/graphiql |
| GraphQL APIGraphQL API | http://localhost:5678/graphql | http://your_docker_machine_ip:5678/graphql |
| PostgreSQL DatabasePostgreSQL 数据库 | host: localhost, port: 5432主机:localhost,端口:5432 | host: your_docker_machine_ip, port: 5432主机:your_docker_machine_ip,端口:5432 |
If you run Docker Toolbox on Windows Home, you can get your Docker
machine IP address with the command $ docker-machine ip default.
如果你在 Windows 家庭版上使用 Docker Toolbox,可以通过命令 $ docker-machine ip default 获取 Docker 虚拟机的 IP 地址。
Re-initialize The Database重新初始化数据库
In case you do changes to the database schema by modifying the files in
/db/init, you will need to re-initialize the database to see these changes.
This means you need to delete the Docker Volume, the database Docker Image and
rebuild it.
如果你修改了 /db/init 中的文件以变更数据库 schema,则需要重新初始化数据库才能使更改生效。这意味着你需要删除对应的 Docker 卷和数据库 Docker 镜像,然后重新构建。
# Stop running containers
docker-compose down
# List Docker volumes
docker volume ls
# Delete volume
docker volume rm <your_repository_name>_db
# Delete database image to force rebuild
docker rmi db
# Run containers (will automatically rebuild the image)
docker-compose up
Add Custom Plugin添加自定义插件
wrapPlans使用 wrapPlans
This section is optional but describes how to wrap a plan generated by
PostGraphile in order to customize it. Create a new folder graphql/plugins
and add a wrap-plans.ts file:
本节为可选内容,介绍如何封装(wrap)PostGraphile 生成的执行计划(plan)以实现自定义逻辑。新建 graphql/plugins 文件夹,并添加一个 wrap-plans.ts 文件:
import { sideEffect } from "postgraphile/grafast";
import { wrapPlans } from "postgraphile/utils";
export default wrapPlans({
Mutation: {
createUser(plan) {
const $result = plan();
const $user = $result.get("user");
sideEffect($user, (user) => {
console.info("Created user:", user?.username);
});
return $result;
},
},
});
Now update graphile.config.ts to import and register the plugin:
接着更新 graphile.config.ts,导入并注册该插件:
import { PostGraphileAmberPreset } from "postgraphile/presets/amber";
import { makePgService } from "postgraphile/adaptors/pg";
import WrapPlansPlugin from "./plugins/wrap-plans.ts";
export default {
extends: [PostGraphileAmberPreset],
pgServices: [makePgService({ connectionString: process.env.DATABASE_URL })],
plugins: [WrapPlansPlugin],
};
Finally rebuild and rerun the GraphQL container.
最后重新构建并启动 GraphQL 容器:
# Shut down containers
docker-compose down
# Rebuild the GraphQL container
docker-compose build graphql
# Rerun containers
docker-compose up
If you execute a createUser mutation like in the example provided below, you
will notice the log messages from the custom plugin printing in your terminal.
如果你按照下文示例执行 createUser mutation,就会在终端中看到该自定义插件输出的日志信息。
Queries And Mutations Examples查询与变更示例
Queries查询(Query)
Example of query to get all posts and their author.
获取所有帖子及其作者信息的查询示例:
query {
allPosts {
nodes {
id
title
body
userByAuthorId {
username
}
}
}
}
Mutations变更(Mutation)
Example of mutation to create a new user.
创建新用户的变更示例:
mutation {
createUser(input: { user: { username: "Bob" } }) {
user {
id
username
createdDate
}
}
}