My flask application is below:
from flask import Flask, request, jsonify
import docker
import os
import uuid
app = Flask(__name__)
client = docker.from_env()
@app.route('/run', methods=['POST'])
def run_code():
data = request.json
code = data.get('code')
try:
output = execute_code("python", code)
return jsonify({'output': output})
except Exception as e:
return jsonify({'error': str(e)}), 500
def execute_code(language, code):
code_file, command = create_code_file(language, code) # just writes the code to a file and path to that is code_file
container = client.containers.run(
"python:3.9-slim",
command,
volumes={os.path.abspath(code_file): {'bind': f'/code/{code_file}', 'mode': 'ro'}},
working_dir='/code',
detach=True
)
result = container.wait()
output = container.logs().decode('utf-8')
container.remove()
os.remove(code_file)
if result['StatusCode'] != 0:
raise Exception(output)
return output
if __name__ == '__main__':
app.run(host='0.0.0.0', port=5000)
I want to deploy the above by building a dockerfile. Can someone give me a docker file that will be suitable for this.
I tried the below docker file:
FROM docker:19.03.12
RUN apk add --no-cache python3-dev py3-pip gcc musl-dev libffi-dev openssl-dev
WORKDIR /app
COPY . /app
RUN pip3 install flask docker
CMD ["sh", "-c", "dockerd-entrypoint.sh & python3 test_code.py"]
It is building successfully, but not running at all. I am getting the below error:
sh: dockerd-entrypoint.sh: not found
Traceback (most recent call last):
File "/usr/lib/python3.8/site-packages/urllib3/connection.py", line 198, in _new_conn
sock = connection.create_connection(
File "/usr/lib/python3.8/site-packages/urllib3/util/connection.py", line 60, in create_connection
for res in socket.getaddrinfo(host, port, family, socket.SOCK_STREAM):
File "/usr/lib/python3.8/socket.py", line 918, in getaddrinfo
for res in _socket.getaddrinfo(host, port, family, type, proto, flags):
socket.gaierror: [Errno -3] Try again
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/usr/lib/python3.8/site-packages/urllib3/connectionpool.py", line 793, in urlopen
response = self._make_request(
File "/usr/lib/python3.8/site-packages/urllib3/connectionpool.py", line 496, in _make_request
conn.request(
File "/usr/lib/python3.8/site-packages/urllib3/connection.py", line 400, in request
self.endheaders()
File "/usr/lib/python3.8/http/client.py", line 1247, in endheaders
self._send_output(message_body, encode_chunked=encode_chunked)
File "/usr/lib/python3.8/http/client.py", line 1007, in _send_output
self.send(msg)
File "/usr/lib/python3.8/http/client.py", line 947, in send
self.connect()
File "/usr/lib/python3.8/site-packages/urllib3/connection.py", line 238, in connect
self.sock = self._new_conn()
File "/usr/lib/python3.8/site-packages/urllib3/connection.py", line 205, in _new_conn
raise NameResolutionError(self.host, self, e) from e
urllib3.exceptions.NameResolutionError: <urllib3.connection.HTTPConnection object at 0x7b6a0588d100>: Failed to resolve 'docker' ([Errno -3] Try again)
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/usr/lib/python3.8/site-packages/requests/adapters.py", line 667, in send
resp = conn.urlopen(
File "/usr/lib/python3.8/site-packages/urllib3/connectionpool.py", line 847, in urlopen
retries = retries.increment(
File "/usr/lib/python3.8/site-packages/urllib3/util/retry.py", line 515, in increment
raise MaxRetryError(_pool, url, reason) from reason # type: ignore[arg-type]
urllib3.exceptions.MaxRetryError: HTTPConnectionPool(host='docker', port=2375): Max retries exceeded with url: /version (Caused by NameResolutionError("<urllib3.connection.HTTPConnection object at 0x7b6a0588d100>: Failed to resolve 'docker' ([Errno -3] Try again)"))
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/usr/lib/python3.8/site-packages/docker/api/client.py", line 223, in _retrieve_server_version
return self.version(api_version=False)["ApiVersion"]
File "/usr/lib/python3.8/site-packages/docker/api/daemon.py", line 181, in version
return self._result(self._get(url), json=True)
File "/usr/lib/python3.8/site-packages/docker/utils/decorators.py", line 44, in inner
return f(self, *args, **kwargs)
File "/usr/lib/python3.8/site-packages/docker/api/client.py", line 246, in _get
return self.get(url, **self._set_request_timeout(kwargs))
File "/usr/lib/python3.8/site-packages/requests/sessions.py", line 602, in get
return self.request("GET", url, **kwargs)
File "/usr/lib/python3.8/site-packages/requests/sessions.py", line 589, in request
resp = self.send(prep, **send_kwargs)
File "/usr/lib/python3.8/site-packages/requests/sessions.py", line 703, in send
r = adapter.send(request, **kwargs)
File "/usr/lib/python3.8/site-packages/requests/adapters.py", line 700, in send
raise ConnectionError(e, request=request)
requests.exceptions.ConnectionError: HTTPConnectionPool(host='docker', port=2375): Max retries exceeded with url: /version (Caused by NameResolutionError("<urllib3.connection.HTTPConnection object at 0x7b6a0588d100>: Failed to resolve 'docker' ([Errno -3] Try again)"))
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "test_code.py", line 6, in <module>
client = docker.from_env()
File "/usr/lib/python3.8/site-packages/docker/client.py", line 94, in from_env
return cls(
File "/usr/lib/python3.8/site-packages/docker/client.py", line 45, in __init__
self.api = APIClient(*args, **kwargs)
File "/usr/lib/python3.8/site-packages/docker/api/client.py", line 207, in __init__
self._version = self._retrieve_server_version()
File "/usr/lib/python3.8/site-packages/docker/api/client.py", line 230, in _retrieve_server_version
raise DockerException(
docker.errors.DockerException: Error while fetching server API version: HTTPConnectionPool(host='docker', port=2375): Max retries exceeded with url: /version (Caused by NameResolutionError("<urllib3.connection.HTTPConnection object at 0x7b6a0588d100>: Failed to resolve 'docker' ([Errno -3] Try again)"))
If anyone is having any experience building docker-in-docker type of things or have previously build an online compiler you may help me here.
New contributor
Sujai Kumar Gupta is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.