Skip to main content

Running PostGraphile as a Library in Docker

Untested!尚未经过实测!

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 running PostGraphile.

本指南将介绍如何在本地机器上运行一组相互连通的 Docker 容器,包括一个 PostgreSQL 数据库容器和一个运行 PostGraphile 的容器。

It is following the same use case as the guide Running PostGraphile in Docker with one difference, the PostGraphile container runs a Node.js application using PostGraphile as library instead of running PostGraphile via CLI. Running PostGraphile as a library opens doors to greater customization possibilities.

本文沿用了 在 Docker 中运行 PostGraphile 一文中的相同示例,唯一区别在于:PostGraphile 容器运行的不是通过 CLI 启动的 PostGraphile,而是一个将 PostGraphile 作为库使用的 Node.js 应用。以库形式运行 PostGraphile 可以为你开启更丰富的定制能力。

Follow the steps provided in the guide Running PostGraphile in Docker and come back to this guide to create the GraphQL container.

请先按照 在 Docker 中运行 PostGraphile 指南中的步骤操作,完成后再回到本指南来创建 GraphQL 容器。

Create PostGraphile Container创建 PostGraphile 容器​

At this stage, the repository should look like this:

此时,代码仓库的目录结构应如下所示:

/
├─ db/
| ├─ init/
| | ├─ 00-database.sql
| | └─ 01-data.sql
| └─ Dockerfile
├─ .env
└─ docker-compose.yml

Update Environment Variables更新环境变量​

Update the file .env to add the DATABASE_URL which will be used by PostGraphile to connect to the PostgreSQL database. Note the DATABASE_URL follows the syntax postgres://<user>:<password>@db:5432/<db_name>.

更新 .env 文件,添加 PostGraphile 用于连接 PostgreSQL 数据库的 DATABASE_URL。请注意,DATABASE_URL 遵循 postgres://<user>:<password>@db:5432/<db_name> 的格式。

[...]
# GRAPHQL
# Parameters used by graphql container
DATABASE_URL=postgres://postgres:change_me@db:5432/forum_example

Create Node.js Application创建 Node.js 应用​

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. In the graphql folder, create a subfolder src and add a file package.json (plus a lockfile such as package-lock.json) into it with the following content.

在仓库根目录下新建一个 graphql 文件夹,用于存放构建 PostGraphile 容器所需的文件。在 graphql 文件夹中再创建一个 src 子文件夹,并在其中添加如下内容的 package.json 文件(以及对应的锁文件,例如 package-lock.json)。

graphql/src/package.json
{
"name": "postgraphile-as-library",
"private": true,
"type": "module",
"dependencies": {
"postgraphile": "^5.0.0"
}
}

This file will be used by NPM package manager to install the dependencies in the Node.js container.

NPM 包管理器将使用该文件在 Node.js 容器内安装依赖。

Create a graphile.config.js file in the graphql/src folder:

在 graphql/src 文件夹中创建一个 graphile.config.js 文件:

graphql/src/graphile.config.ts
import { PostGraphileAmberPreset } from "postgraphile/presets/amber";
import { makePgService } from "postgraphile/adaptors/pg";

const preset = {
extends: [PostGraphileAmberPreset],
pgServices: [makePgService({ connectionString: process.env.DATABASE_URL })],
grafserv: {
port: 5678,
},
} satisfies GraphileConfig.Preset;

export default preset;

In the same graphql/src folder, create a new file server.ts with the following content.

在同一个 graphql/src 文件夹中,再新建一个 server.ts 文件,内容如下:

graphql/src/server.ts
import { createServer } from "node:http";
import { postgraphile } from "postgraphile";
import { grafserv } from "postgraphile/grafserv/node";
import preset from "./graphile.config.ts";

const pgl = postgraphile(preset);
const serv = pgl.createServ(grafserv);

const server = createServer();
serv.addTo(server).then(
() => void server.listen(preset.grafserv.port),
(e) => {
console.error(e);
process.exit(1);
},
);

Create PostGraphile Dockerfile创建 PostGraphile Dockerfile​

Create a new file Dockerfile in the graphql folder (not in the folder src) with the following content.

在 graphql 文件夹下(注意不要放在 src 子文件夹中)新建一个 Dockerfile 文件,内容如下:

graphql/Dockerfile
FROM node:24-alpine

# Set Node.js app folder
RUN mkdir -p /home/node/app/node_modules
WORKDIR /home/node/app

# Copy dependencies
COPY ./src/package.json ./src/package-lock.json .
RUN chown -R node:node /home/node/app

# Install dependencies
USER node
RUN npm install

# Copy application files and config
COPY --chown=node:node ./src .

EXPOSE 8080
CMD [ "node", "server.ts" ]

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/
| ├─ src/
| | ├─ package.json
| | ├─ package-lock.json
| | ├─ graphile.config.ts
| | └─ server.ts
| └─ 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. Note 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 卷(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. Note 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 地址。

Container容器Docker on Linux / Windows ProLinux / Windows 专业版上的 DockerDocker on Windows HomeWindows 家庭版上的 Docker
GraphQL API DocumentationGraphQL API 文档http://localhost:5678/graphiqlhttp://your_docker_machine_ip:5678/graphiql
GraphQL APIGraphQL APIhttp://localhost:5678/graphqlhttp://your_docker_machine_ip:5678/graphql
PostgreSQL DatabasePostgreSQL 数据库host: localhost, port: 5432主机:localhost,端口:5432host: your_docker_machine_ip, port: 5432主机:your_docker_machine_ip,端口:5432

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