У нас есть простое приложение на Python: REST-контроллер, возвращающий JSON.
Здесь: https://github.com/NikaGolybeva/smt
Контроллер:
#!flask/bin/python
from flask import Flask, jsonify
app = Flask(__name__)
tasks = [
{
'id': 1,
'title': u'Buy groceries',
'description': u'Milk, Cheese, Pizza, Fruit, Tylenol',
'done': False
},
{
'id': 2,
'title': u'Learn Python',
'description': u'Need to find a good Python tutorial on the web',
'done': False
}
]
from flask import abort
@app.route('/test', methods=['GET'])
def get_tasks():
return jsonify({'tasks': tasks})
@app.route('/test/<int:task_id>', methods=['GET'])
def get_task(task_id):
task = list(filter(lambda t: t['id'] == task_id, tasks))
if len(task) == 0:
abort(404)
return jsonify({'task': task[0]})
if __name__ == '__main__':
app.run(debug=True)
Dockerfile:
FROM python:3.7
EXPOSE 5000
ADD run.py /
RUN pip install pystrich
RUN pip install flask
CMD [ "python", "./run.py" ]
Мы запускаем приложение с докером на порту 5000:
v-chernyshov@v-chernyshov:~/IdeaProjects/smt$ docker build -t smt .
...
v-chernyshov@v-chernyshov:~/IdeaProjects/smt$ docker run -p 5000:5000 smt
* Serving Flask app "run" (lazy loading)
* Environment: production
WARNING: This is a development server. Do not use it in a production deployment.
Use a production WSGI server instead.
* Debug mode: on
* Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)
* Restarting with stat
* Debugger is active!
* Debugger PIN: 309-988-075
Ожидаем, что когда мы попытаемся отправить запрос на http://localhost:5000/test/1
, приложение вернет JSON.Но на самом деле приложение недоступно.
Хорошо.Вариант 2.
Добавление приложения в docker-compose.yml и развертывание на виртуальном сервере.docker-compose выглядит так:
services:
web:
image: account/front:0.0.1
restart: on-failure
ports:
- 80:3000
back:
image: account/back:0.0.3
restart: on-failure
ports:
- 8099:8099
smth:
image: nikagolybeva/smth:0.0.1
restart: on-failure
ports:
- 5000:5000
Мы вернулись на Java и что-то на Python.Я написал метод, который пытается отправить запрос в smtn REST раз в минуту:
@Scheduled(initialDelay = 1000L, fixedDelay = 60000L)
public void testPython() {
String url = "http://smth:5000/test/1";
log.info("testing python, url: {}", url);
PythonTestDto pythonTestDto = restTemplate.getForObject(url, PythonTestDto.class);
String result = "";
try {
result = new ObjectMapper().writeValueAsString(pythonTestDto);
} catch (JsonProcessingException e) {
e.getMessage();
}
log.info("response: {}", result);
}
Запустите его с помощью docker-compose.
back & message развертывается на их портах:
smth_1_f8c6211ef46d | * Serving Flask app "run" (lazy loading)
smth_1_f8c6211ef46d | * Environment: production
smth_1_f8c6211ef46d | WARNING: This is a development server. Do not use it in a production deployment.
smth_1_f8c6211ef46d | Use a production WSGI server instead.
smth_1_f8c6211ef46d | * Debug mode: on
smth_1_f8c6211ef46d | * Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)
smth_1_f8c6211ef46d | * Restarting with stat
smth_1_f8c6211ef46d | * Debugger is active!
smth_1_f8c6211ef46d | * Debugger PIN: 769-002-661
...
back_1_9622a732ea20 | 2019-09-26 08:16:31.725 INFO 1 --- [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat started on port(s): 8099 (http) with context path ''
Ping что-то со спины:
root@kvm1:/home/xpendence/docker# docker-compose exec back ping smth
PING smth (172.21.0.3): 56 data bytes
64 bytes from 172.21.0.3: seq=0 ttl=64 time=0.396 ms
64 bytes from 172.21.0.3: seq=1 ttl=64 time=0.142 ms
64 bytes from 172.21.0.3: seq=2 ttl=64 time=0.175 ms
64 bytes from 172.21.0.3: seq=3 ttl=64 time=0.195 ms
64 bytes from 172.21.0.3: seq=4 ttl=64 time=0.113 ms
64 bytes from 172.21.0.3: seq=5 ttl=64 time=0.127 ms
64 bytes from 172.21.0.3: seq=6 ttl=64 time=0.521 ms
^C
--- smth ping statistics ---
7 packets transmitted, 7 packets received, 0% packet loss
round-trip min/avg/max = 0.113/0.238/0.521 ms
Это нормально, но попытка отправить запрос по REST не удалась:
back_1_9622a732ea20 | org.springframework.web.client.ResourceAccessException: I/O error on GET request for "http://smth:5000/test/1": Connection refused (Connection refused); nested exception is java.net.ConnectException: Connection refused (Connection refused)
Скажите, пожалуйста, что не так