有一个码头网络:docker network create nginx-proxy
然后两个 Web 服务器在 Docker 容器中运行。
- 第一个容器,包含一个公开 API 的网络服务器(仅供同一 docker 网络上的其他应用程序使用)。
docker-compose
文件:
version: '3'
services:
my-api:
image: node:alpine
volumes:
- ./:/api
working_dir: /api
command: npm run start
networks:
default:
external:
name: nginx-proxy
- 第二个容器包含一个使用 API 的应用程序。
docker-compose
文件:
version: '3'
services:
my-app:
image: node:alpine
environment:
API_URL: ???
volumes:
- ./:/app
working_dir: /app
command: npm run start
networks:
default:
external:
name: nginx-proxy
在这个 nodejs 应用程序的代码中,它尝试使用如下代码连接到 API:
const fetch = require('node-fetch')
const apiUrl = process.env.API_URL
const getSomethingFromApi = jsonArgs =>
fetch(apiUrl, {
method: 'post',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(jsonArgs)
})
.then(response => response.json())
如何为第二个容器中的应用程序配置 docker 文件以使用第一个容器中的 API?