[英]trying to build docker container with docker compose, running a vite + react + ts app throws an error
[英]container not reachable in docker compose simplest example
服務的每個容器都加入 default.network 並且可以被該網絡上的其他容器訪問,並且可以被它們在與容器名稱相同的主機名處發現。
但我創建了一個非常簡單的應用程序,但我無法開始工作。 我的腳本是:(也在這里)
frontend/index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>test</title>
</head>
<body>
<button id="btn">Hit me</button>
<script type="module" src="/src/main.js"></script>
</body>
</html>
frontend/src/main.ts
async function btn(): Promise<void> {
console.log("Button clicked")
const content = await (await fetch("http://backend/")).json()
console.log(content)
}
document.getElementById("btn")!.addEventListener("click", btn);
(默認tsc --init
)
backend/app/main.py
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
app = FastAPI()
origins = ["*"]
app.add_middleware(
CORSMiddleware,
allow_origins=origins,
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
@app.get("/")
def read_root():
return {"Hello": "World"}
backend/Dockerfile
FROM python:latest
WORKDIR /code
COPY ./requirements.txt /code/requirements.txt
RUN pip install --no-cache-dir --upgrade -r /code/requirements.txt
COPY ./app /code/app
CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "80"]
backend/requirements.txt
fastapi
uvicorn
最后compose.yaml
services:
backend:
build: ./backend/.
ports:
- "80"
frontend:
image: nginx:latest
volumes:
- ./frontend:/usr/share/nginx/html
ports:
- "8002:80"
當我按照文檔的建議按下按鈕時,我希望達到http://backend/
,但我得到GET http://backend/.net::ERR_NAME_NOT_RESOLVED
。 我應該如何從前端訪問后端,反之亦然?
你對 docker.networks 很緊張,但你的前端代碼不在 docker 容器中運行,它在瀏覽器中運行。 在您的示例中,您在端口 80 上公開了 API,因此從 tyoescript 代碼中,您應該能夠連接到http://localhost
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.