onuryartasi
onuryartasi

Reputation: 597

Docker-compose access container with service name in python file?

I have a two container and How I can access another container in python file with django web server

Docker-compose.yml file

version: '2'

services:

  web:
    build: ./web/
    command: python3 manage.py runserver 0.0.0.0:8001
    volumes:
      - ./web:/code
    ports:
      - "8001:80"
    networks:
      - dock_net
    container_name: con_web
    depends_on:
      - "api"
    links:
      - api
  api:
    build: ./api/
    command: python3 manage.py runserver 0.0.0.0:8000
    volumes:
      - ./api:/code
    ports:
      - "8000:80"
    networks:
      - dock_net
    container_name: con_api

networks:
  dock_net:
      driver: bridge

Python File:

I can get mail_string from form

   mail = request.POST.get('mail_string', '') 
   url = 'http://con_api:8000/api/'+mail+'/?format=json'
   resp = requests.get(url=url)         
   return HttpResponse(resp.text)

I request api container and get value but I dont know ip address

Upvotes: 4

Views: 3586

Answers (1)

Ayushya
Ayushya

Reputation: 10417

Updated Answer

In your python file, you can use url = 'http://api/'+mail+'/?format=json'. This will enable you to access the url you are trying to get request from.

Original Answer

If the two containers are independent, then you can create a network and when you make both the containers a part of same network then you can access them using their hostname which you can specify by --hostname=HOSTNAME.


Another easy way is to use docker-compose file which creates a network by default and all the services declared in the file are a part of that network. By that you can access other services by their service name. Simply like http://container1/ when your docker-compose file is like this:

version: '3'
services:

  container1:
    image: some_image

  container2:
    image: another_or_same_image

Now enter into container2 by:

docker exec -it container2 /bin/bash

and run ping http://contianer1

You will receive packets and therefore be able to access other container.

Upvotes: 2

Related Questions