Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
702 views
in Technique[技术] by (71.8m points)

docker - How to start Dockerized Python Flask app with https instead of http?

I have a REST api server developed with Python & Flask framework and deployed in the main server with Docker. When I build & start the docker container by sudo docker-compose build & sudo docker-compose up, the docker container starts at http://0.0.0.0:5000/ or localhost and using port 5000.

This works fine in non-ssl environment or browser or domain. But recently my main website (suppose www.example.com) started using ssl certificates. To communicate with main site I have to serve my apis in https instead of http.

Now I am trying to use this code to start server in https mode, but getting some errors.

My code :

import ssl
ctx = ssl.SSLContext(ssl.PROTOCOL_SSLv23)
ctx.load_cert_chain('certificate.pem', 'privateKey.pem')

.
.

if __name__ == "__main__":
    app.run(debug=True, host='0.0.0.0',ssl_context=ctx)

Here is my error:

enter image description here

What will be the proper procedure to start Docker supported Python Flask app in https mode?

question from:https://stackoverflow.com/questions/65901178/how-to-start-dockerized-python-flask-app-with-https-instead-of-http

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

After 2 days of tiresome work I found the proper solution. My domain got 2 files when implemented ssl or https. One is mydomain_com.crt file, another is private.key

I found these 2 files in my server's main directory. As I am using Apache, then I found these files in /etc/var/www/html folder.

I copied 2 files as follows:

  1. copied the license from mydomain_com.crt file and paste in a text file then renamed it certificate.pem

  2. copied the license from private.key and paste in a text file then renamed it privateKey.pem

Then I used my domain's default ssl certificate into my Flask app like this:

import ssl
ctx = ssl.SSLContext(ssl.PROTOCOL_SSLv23)
ctx.load_cert_chain('certificate.pem', 'privateKey.pem')
.
.
.
if __name__ == "__main__":
    app.run(debug=True, host='0.0.0.0', ssl_context=ctx)

And exposed the 2 ports in my Dockerfile like this :

FROM python:3
WORKDIR /usr/src/app
COPY requirements.txt ./
RUN pip install --no-cache-dir -r requirements.txt
COPY . .
CMD [ "python", "app.py" ]
EXPOSE 80
EXPOSE 443

After restart, my Dockerized Flask app now working with my domain's default ssl certificate and serving the APIs correctly.

Example : https:mydomain.com:5000/getUsers


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...