Good day! I wrote client and server applications, I run them via docker, but client app couldn't connect to server.
Client's code:
import requests
import json
class Client:
def attach_comp_to_employee(self, employee_id, company):
try:
res = requests.get('http://0.0.0.0:8080/',
data=json.dumps({"action": "comp_to_employee",
"id": employee_id,
"company": company,
"owner_name": self.user,
"dbname": self.dbname,
"password": self.password}),
timeout=3)
except requests.exceptions.ConnectionError:
res = "Can't connect to server."
except requests.exceptions.Timeout:
res = "Time for connection expired."
finally:
return res
cl = Client("test_user1", "shop", "password1")
print("Send...")
res = cl.attach_comp_to_employee(6, "ABCD")
print(res)
Server's code:
from aiohttp import web
class Service:
def __init__(self):
self.app = web.Application()
self.app.add_routes([web.get('/', self.handler)])
async def handler(self, request):
return web.json_response({"response": "Hi"})
print("Start...")
ser = Service()
web.run_app(ser.app)
I created two dockerfiles for them.
Dockerfile for client:
FROM python:3
WORKDIR /app
ADD . /app
RUN pip3 install requests
CMD ["python3", "client.py"]
Dockerfile for server:
FROM python:3
WORKDIR /app
ADD . /app
RUN pip3 install aiohttp
CMD ["python3", "server.py"]
Then I created docker-compose.yml:
version: '3'
services:
server:
build: ./server
client:
build: ./client
links:
- "server:localhost"
After all my directory looks like:
project
|___server
| |__Dockerfile
| |__server.py
|__client
| |__Dockerfile
| |__client.py
|__docker_compose.yml
When I run docker-compose up
I see this:
If I interrupt it with Cntr+ C
I will see this:
So the server is running and is waiting for requests.
Help me please. What is wrong in my code? What should I do to connect this two scripts?
your backend container is the server - therefore it needs to listen on specific ports to accept the client requests.
expose ports in your Dockerfile:
FROM python:3
WORKDIR /app
ADD . /app
RUN pip3 install aiohttp
EXPOSE 8080
CMD ["python3", "server.py"]
now, as a side note, as @Klaus D. commented out, -the docker-compose links
option shouldn't be in use any more. instead, in your code, refer directly to the server container name.
good luck!