![](/img/trans.png)
[英]Communication between nodejs express server and docker containers
[英]How to proxy Vue client to Express server running in docker containers
我正在嘗試使用vue cli3應用程序與我在單獨的docker容器中運行的node express api交談。 在本地,我只是在vue.config文件中添加一個配置來代理我的開發服務器,我在嘗試模擬容器之間的這個功能時遇到了麻煩。
我已經為服務器和客戶端設置了一個dockerfile,並從docker-compose.yml文件中運行它們。 客戶端運行正常,但在向快速服務器發出請求時,網絡選項卡使用端口5001顯示它。服務器也在運行,可以在端口3001訪問。
我正在嘗試在vue.config.js中復制的功能
module.exports = {
devServer: {
port: 5001,
proxy: {
'/api': {
target: 'http://localhost:3001'
}
}
},
}
客戶端Dockerfile
# build stage
FROM node:lts-alpine as build-stage
WORKDIR /app
COPY package*.json ./
RUN npm install
COPY . .
RUN npm run build
# production stage
FROM nginx:stable-alpine as production-stage
COPY --from=build-stage /app/dist /usr/share/nginx/html
EXPOSE 80
CMD ["nginx", "-g", "daemon off;"]
服務器Dockerfile
# develop stage
FROM node:11-alpine as develop-stage
WORKDIR /app/server
COPY package*.json ./
RUN npm install
COPY . .
EXPOSE 3001
CMD ["npm", "run", "start"]
泊塢窗,compose.yml
version: '3.7'
services:
client:
build: ./
volumes:
- ./:/app
- /node_modules
ports:
- 8080:80
- 5001:80
container_name: client
depends_on:
- api
links:
- api
api:
build: ./server
volumes:
- ./server:/server
- /server/node_modules
ports:
- 3001:3001
container_name: api
nginx.conf
user nginx;
worker_processes 1;
error_log /var/log/nginx/error.log warn;
pid /var/run/nginx.pid;
events {
worker_connections 1024;
}
http {
include /etc/nginx/mime.types;
default_type application/octet-stream;
log_format main '$remote_addr - $remote_user [$time_local] "$request" '
'$status $body_bytes_sent "$http_referer" '
'"$http_user_agent" "$http_x_forwarded_for"';
access_log /var/log/nginx/access.log main;
sendfile on;
keepalive_timeout 65;
upstream rest_api {
server api:3001;
}
server {
listen 80;
server_name localhost;
location / {
root /app;
index index.html;
try_files $uri $uri/ /index.html =404;
}
location /api {
proxy_pass http://rest_api;
# rewrite ^/api(.*)$ $1 break;
}
}
如果有幫助,這就是他們在運行docker compose后看起來的樣子
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
81e894bf4671 wiley_client "nginx -g 'daemon of…" 3 hours ago Up 3 hours 0.0.0.0:5001->80/tcp, 0.0.0.0:8080->80/tcp client
4941260708b4 wiley_api "docker-entrypoint.s…" 3 hours ago Up 3 hours 0.0.0.0:3001->3001/tcp api
我希望/ api上的任何客戶端請求都可以在我的服務器docker容器上移植到3001,而不是像目前那樣移植到5001。
好吧,好像我沒有注入我的nginx.conf文件所以更改了Client Dockerfile
# production stage
FROM nginx:stable-alpine as production-stage
RUN apk add --update --upgrade --no-cache wget
ADD ./nginx.conf /etc/nginx/nginx.conf <-- added this line
COPY --from=build-stage /app/dist /usr/share/nginx/html
EXPOSE 80
然后在nginx.conf中,確保它指向我構建的index.html文件
location / {
root /app/dist; <-- add dist here
index index.html;
try_files $uri $uri/ /index.html =404;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.