how to make a non-hardcoded URL path in docker image to call backend service?

I’m new in docker. Let me describe my scenario:
I made 2 docker images for a web application. one image is front-end web layer for presentation and the other is back-end layer supplying REST service.

So I need to run 2 containers for this 2 images. the front-end calls services in back-end. Now I need to write the back-end’s URL in front-end’s code and build the image…I don’t think this is the right way for micro service…

  • Docker php5-fpm service exited (code 0)
  • Docker build auth error
  • 'Too many levels of symbolic links' in /usr/local/bin after performing docker pull
  • I need to run my node app using this Docker file
  • docker nginx connection refused while connecting to upstream
  • Not able to debug on docker container with PyCharm 5
  • because if my laptop’s IP changes or others want to use my image,they cannot get the service…So how can I make the URL variable and make my front-end image can be used for others without rebuild?

    Thx!

  • Bulk Container image pull without “docker pull”
  • Docker, ipc resources and '--privilaged' option
  • can't delete glassfish directory in docker container
  • Committing a running docker container (with pause), then run it, what's the images internal state
  • How to access lower layer files in docker?
  • Let users enter Python code and run it on a Rails website
  • 2 Solutions collect form web for “how to make a non-hardcoded URL path in docker image to call backend service?”

    You can do this by passing an environment variable to the docker container when you run it.

    something like this:

    docker run --name frontend -e MY_APP_BACKEND_IP="192.168.7.2" -e MY_APP_BACKEND_PORT="3000" ...
    

    And on the back-end, let’s say you are using NodeJS, you can do:

    var backend_ip   = process.env.MY_APP_BACKEND_IP;
    

    Note: Not a NodeJS pro, but some googling showed me how to do it

    As of Docker 1.10 you can use networking. What this does is binds the ip address of the docker container to a hostname that can be used in the container.

    If you use docker-compose, a network is automatically created and the two services can talk to one another. Here is an example of one:

    version: "2"
    
    services:
      frontend:
        image: nginx
        networks:
          - my-network
        environment:
          BACKEND_URL: "http://backend"
      backend:
        image: mariadb
        networks:
          - my-network
        environment:
          FRONTEND_URL: "http://frontend"
    
    networks:
      my-network:
        driver: bridge
    

    You can read more about this in the Getting started with multi-host networking available here or you can follow a guide like this Composing Multi-container Networks with Docker Compose

    Docker will be the best open platform for developers and sysadmins to build, ship, and run distributed applications.