我正在尝试将一个2容器的docker-compose应用程序部署到Azure,由前端和后端/API组成。我需要前端容器使用fetch方法与后端容器通信,以使用REST API检索一些数据。
部署后,我首先得到:
“阻止加载混合活动内容“http://backend:9000/api/weather””
那么一旦我暂时禁用保护,错误将变为
“跨域请求被阻止:同源策略不允许阅读http://backend:9000/api/weather上的远程资源。(原因:CORS请求未成功)。状态代码:(null)."。
这是我的docker-compose.yml:
version: "3.8"
services:
frontend:
image: my_frontend_image
build:
context: .
container_name: frontend
ports:
- "80:8000"
environment:
- PORT=8000
- ENDPOINT=http://backend:9000/api
- HOST=0.0.0.0
backend:
image: my_backend_image
build:
context: .
container_name: backend
environment:
- PORT=9000
- MAP_ENDPOINT=http://api.openweathermap.org/data/2.5
- TARGET_CITY=Helsinki,fi
- APPID=my_api_key
前端容器暴露端口8000,后端容器在其各自的Dockerfile中暴露9000。
我的后端使用kcors:
index.js
const cors = require('kcors');
const app = new Koa();
app.use(cors());
和koa路由器:
index.js
const port = process.env.PORT;
const router = require('koa-router')();
router.get('/api/weather', async ctx => {
const weatherData = await fetchWeather();
ctx.type = 'application/json; charset=utf-8';
ctx.body = weatherData.weather ? weatherData.weather[0] : {};
});
app.use(router.routes());
app.use(router.allowedMethods());
app.listen(port);
我的前端请求看起来像这样:
index.jsx:
const baseURL = process.env.ENDPOINT;
const getWeatherFromApi = async () => {
try {
const response = await fetch(`${baseURL}/weather`);
return response.json();
} catch (error) {
console.error(error);
}
return {};
};
webpack.config.js:
const GLOBALS = {
'process.env.ENDPOINT': JSON.stringify(process.env.ENDPOINT || 'http://0.0.0.0:9000/api'),
};
module.exports = {
...
plugins: [
...
new webpack.DefinePlugin(GLOBALS),
]
};
我设法让应用程序在本地工作,通过将我的API端点设置为http://localhost:9000/api并在我的docker-compose中Map“9000:9000”。但是我不能让它在云中工作。
在本地,我尝试从彼此内部ping每个容器,这没有问题。
docker exec -it frontend bash
root@e87994510b0e:/app# ping backend
PING backend (172.25.0.2) 56(84) bytes of data.
64 bytes from backend.efi-recruitment_default (172.25.0.2): icmp_seq=1 ttl=64 time=0.059 ms
64 bytes from backend.efi-recruitment_default (172.25.0.2): icmp_seq=2 ttl=64 time=0.117 ms
64 bytes from backend.efi-recruitment_default (172.25.0.2): icmp_seq=3 ttl=64 time=0.115 ms
尝试使用curl访问API也是有效的:
root@e87994510b0e:/app# curl http://backend:9000/api/weather
{"id":800,"main":"Clear","description":"clear sky","icon":"01n"}
这是我第一次尝试将一些东西部署到Azure,我很迷茫。任何帮助将不胜感激。
1条答案
按热度按时间brccelvz1#
您的前端通过user's browser调用您的后端。您的后台未暴露在互联网上,无法访问。
将您的后端放置在另一个Web App的容器中并更新您的URL。这应该能解决你的问题。