从一个容器到另一个容器进行 API 调用

Make an API call from one container to another

我有一个节点应用程序,一个 next.js 前端应用程序,Redis 和 Postgres 作为数据库。我已将 Next.js 和 node.js 停靠在不同的容器中。 Docker-compose.yaml如下

version: '3'
services: 
  redis-server:
    image: 'redis'
    restart: always
  postgres-server:
    image: 'postgres:latest'
    environment:
      - POSTGRES_USER=postgres
      - POSTGRES_PASSWORD=postgres
      - POSTGRES_DB=postgres
    ports: 
      - "5433:5432"
    volumes:
        - ./docker/postgres/data/data/pg_hba.conf:/var/lib/postgresql/app_data/pg_hba.conf
        - ./src/db/sql/CREATE_TABLES.sql:/docker-entrypoint-initdb.d/CREATE_TABLES.sql
        - ./src/db/sql/INSERT_TO_TABLES.sql:/docker-entrypoint-initdb.d/INSERT_TO_TABLES.sql
        - ./src/db/sql/CREATE_FUNCTIONS.sql:/docker-entrypoint-initdb.d/CREATE_FUNCTIONS.sql
  node-app:
    build: .
    ports: 
      - "4200:4200" 
  client:
    build:
      context: ./client
      dockerfile: Dockerfile
    container_name: client
    restart: always
    volumes:
      - ./:/app
      - /app/node_modules
      - /app/.next
    ports:
      - 3000:3000

当使用 SSR 时,我无法向 localhost:4200 发出请求。现在,我知道这是因为它们在不同的容器中,如果请求不是来自客户端,那么客户端容器正在检查端口 4200 上的服务器。现在,我不确定如何简单地使用容器名称或其他内容来引用容器以对 SSR 数据发出 API 请求(如 fetch('node-app/users')

docker-compose 为 compose 文件中的所有服务设置一个网络。要访问网络中的另一个容器,您可以使用该容器的名称作为主机名,它将解析为正确的 ip。

所以在你的情况下 fetch('http://node-app:4200/users') 应该可以解决问题。