Home > Enterprise >  Best way to prevent direct calls to a microservice hosted in a docker container
Best way to prevent direct calls to a microservice hosted in a docker container

Time:12-18

I have a simple, proof of concept system that has 2 APIs: one act as the gateway and the other is a microservice. I have created docker containers for both and run them together using a docker compose file.

Everything work well, except I am not sure how to restrict the microservice from being called directly.

Here is my compose file:

version: '3.4'

services:
  apigateway:
    image: apigateway
    container_name: api-gateway
    build:
      context: .
      dockerfile: api_gateway/Dockerfile
    ports:
      - 7500:7500
    networks:
      - api-local

  apiadmin:
    image: apiadmin
    container_name: api-admin
    build:
      context: .
      dockerfile: api_admin/Dockerfile
    ports:
      - 7501:7501
    networks:
      - api-local

networks:
  api-local:
    external: true

I can call localhost:7500/some_url and I get back a response. I can also call localhost:7501/some_url and I also get a response. However, I want to prevent clients from calling the 7501 microservice directly. I want all traffic to go through the gateway only.

I can filter the IP in the microservice and reject the connection if not from the gateway IP, but I was wondering if there better approach.

CodePudding user response:

You could try not to expose the microservice port to the host in your docker-compose file, it should be still reachable within the docker network and accessible to the gateway:

version: '3.4'

services:
  apigateway:
    image: apigateway
    container_name: api-gateway
    build:
      context: .
      dockerfile: api_gateway/Dockerfile
    ports:
      - 7500:7500
    networks:
      - api-local

  apiadmin:
    image: apiadmin
    container_name: api-admin
    build:
      context: .
      dockerfile: api_admin/Dockerfile
    networks:
      - api-local

networks:
  api-local:
    external: true

Please, note I removed the port mapping for the apiadmin service.

  • Related