当前客户组件使用
http://localhost:8000/
和服务器组件
http://server:8000
如何修复,以便可以使用相同的URL?
services:
db:
container_name: weatherdb
image: postgres
volumes:
- ./db_data:/var/lib/postgresql/data
- ./init.sql:/docker-entrypoint-initdb.d/init.sql
ports:
- 5432:5432
environment:
POSTGRES_USER: postgres
POSTGRES_PASSWORD: pass
client:
container_name: client
build:
context: ./client
dockerfile: ./Dockerfile
volumes:
- ./client:/app
ports:
- 3000:3000
environment:
- NEXT_PUBLIC_PYTHON_API=http://server:8000
server:
container_name: server
build:
context: ./server
dockerfile: ./Dockerfile
volumes:
- ./server:/usr/src/app
ports:
- "8000:8000"
environment:
DB_NAME: weatherdb
DB_HOST: weatherdb
DB_PORT: 5432
DB_USER: postgres
DB_PASS: pass
depends_on:
- db
volumes:
db_data:
clientdockerfile
FROM node:18-alpine
ENV PNPM_HOME="/pnpm"
ENV PATH="$PNPM_HOME:$PATH"
RUN corepack enable
WORKDIR /app
EXPOSE 3000
CMD ["pnpm", "run", "dev"]
Serverdockerfile
FROM python:3
WORKDIR /usr/src/app
COPY requirements.txt ./
RUN pip install --no-cache-dir -r requirements.txt
EXPOSE 8000
CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "8000", "--reload"]
我试图在服务器和客户端组件中使用相同的URL。 http://server/
ERR_NAME_NOT_RESOLVED
。
http://localhost/
在客户端组件中会导致以下堆栈跟踪TypeError: fetch failed
at node:internal/deps/undici/undici:12625:11
at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
at async Debug (/app/.next/server/chunks/ssr/_85a404._.js:55:21)
如何在应用程序中动态选择正确的URL。样本说
export const getApiUrl = () => {
if (typeof window === 'undefined') {
// Server
return process.env.SERVER_PYTHON_API;
} else {
// Client
return process.env.NEXT_PUBLIC_PYTHON_API;
}
};
然后进行API调用时,请使用该函数获取正确的URL。样本喜欢const fetchData = async () => {
const apiUrl = getApiUrl();
const response = await fetch(`${apiUrl}/your-endpoint`);
const data = await response.json();
return data;
};
您可以使用这两个URL。并更新Docker用两个URL
组成Env
environment:
- NEXT_PUBLIC_PYTHON_API=http://localhost:8000
- SERVER_PYTHON_API=http://server:8000