Reputation: 3677
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:
What will be the proper procedure to start Docker supported Python Flask app in https mode?
Upvotes: 3
Views: 4129
Reputation: 3677
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:
copied the license from mydomain_com.crt file and paste in a text file then renamed it certificate.pem
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://example.com:5000/getUsers
Upvotes: 5