简体   繁体   中英

Only allow access to express app through nginx with docker

So currently I'm running an express server api, I want to only allow access to the api if the user went through the nginx proxy. In my proxy config for nginx it has the following line for connecting to the express app (note that I have more lines in the nginx config for serving other files):

location ~* ^/(api/|test/){
    proxy_pass http://docker-express-app:3000;
}

This lets me go to my custom domain for example: example.com/api/.... and it will get the request correctly. However I can also go to server.ip.here:3000/api/... and it will still get me the information correctly. I want to eliminate the ability for people to type in the server ip and be able to connect to the api.

(Note: for how the actual express app is setup I used express-generator to get it setup and just added some test api routes to see if I could connect to it)

Also note that I am running the express app, and the nginx proxy using docker.

The docker compose looks like so:

version: '3'
services:
  app:
    container_name: docker-express-app
    restart: always
    build: app/
    command: npm start
    ports:
      - 3000:3000

  proxy:
    container_name: nginx-proxy
    restart: always
    build: proxy/
    ports:
      - 80:80
      - 443:443

The proxy Dockerfile:

FROM nginx:alpine
WORKDIR /usr/src/proxy
RUN rm /etc/nginx/conf.d/*
COPY proxy.conf /etc/nginx/conf.d/
COPY views/* ./views/

The express app Dockerfile:

FROM node:latest
WORKDIR /usr/src/app
COPY package.json .
RUN npm install
COPY . .
EXPOSE 3000
CMD [ "npm", "start" ]

All I want to due is ensure that the requests to the api gets routed through the proxy. Is this possible?

Ok I fixed my issue.

I removed the line in the Dockerfile "EXPOSE 3000" and in the docker-compose I removed the line that defines the ports "ports: - 3000:3000" (I also renamed the container name to app). I then added to the proxy service the following: "links: - app:app" then in the proxy I changed the proxy_pass to the url http://app:3000 , and it works as I want it too.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM