My container does not start and logs are empty

Hi team,

I have created a simple Dockerfile as follow

FROM python:3

RUN apt-get update -y &&
apt-get install -y python3-pip python-dev

WORKDIR /app

RUN pip install Flask requests python-dotenv

COPY . .

EXPOSE 5000

CMD [“python”, “./sent_analisys.py”]

It seems that image is built properly but the container does not start and the logs are not available for throubleshooting

1) Docker build
danilo.alexandre@RO-DALEXAND-10 MINGW64 ~/OneDrive - Nuance/Nuance/Udemy/Docker/azure_aci/flask
$ docker build -t analysis_sentiment .
[+] Building 8.7s (10/10) FINISHED
=> [internal] load build definition from Dockerfile 0.1s
=> => transferring dockerfile: 32B 0.1s
=> [internal] load .dockerignore 0.0s
=> => transferring context: 2B 0.0s
=> [internal] load metadata for Docker Hub 8.1s
=> [1/5] FROM Docker Hub 0.0s
=> [internal] load build context 0.0s
=> => transferring context: 26.35kB 0.0s
=> CACHED [2/5] RUN apt-get update -y && apt-get install -y python3-pip python-dev 0.0s
=> CACHED [3/5] WORKDIR /app 0.0s
=> CACHED [4/5] RUN pip install Flask requests python-dotenv 0.0s
=> [5/5] COPY . . 0.1s
=> exporting to image 0.3s
=> => exporting layers 0.2s
=> => writing image sha256:c8edee63f23e65054396b69f1cae5459245b726fa359ff7dae5410284ab9fc28 0.0s
=> => naming to Docker Hub 0.0s

Use ‘docker scan’ to run Snyk tests against images to find vulnerabilities and learn how to fix them

danilo.alexandre@RO-DALEXAND-10 MINGW64 ~/OneDrive - Nuance/Nuance/Udemy/Docker/azure_aci/flask

2) Docker Run
danilo.alexandre@RO-DALEXAND-10 MINGW64 ~/OneDrive - Nuance/Nuance/Udemy/Docker/azure_aci/flask
$ docker run -d -p 5001:5000 --name analysis_sent_container analysis_sentiment
d3b254aa054b8bdf3935c9cf2a2c055d9304f393ce393d3ecaf5deb0361b2689

3) Docker ps
danilo.alexandre@RO-DALEXAND-10 MINGW64 ~/OneDrive - Nuance/Nuance/Udemy/Docker/azure_aci/flask
$ docker ps
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES

3) Logs are empty

danilo.alexandre@RO-DALEXAND-10 MINGW64 ~/OneDrive - Nuance/Nuance/Udemy/Docker/azure_aci/flask
$ docker logs analysis_sent_container

Phyton app (sent_analisys.py) for your reference:

#from os import name
from flask import Flask
from flask import request
import json
import requests

from dotenv import load_dotenv
import os

app = Flask(name)

@app.route(‘/sentimentAnalysis’, methods=[‘GET’,‘POST’])
def sentiment_analysis():

Gets the input json from the Mix request

try:
    userText = ''
    sourceLanguage = ''
    mixContent = request.get_json(force=True)
    userText = mixContent['userText']
    sourceLanguage = mixContent['sourceLanguage']
    print('teste')        
except:
    None, print ("stopped here")

#Azure API EndPoint
sentimentAnalysesEndPoint = 'https://testing-language-service.cognitiveservices.azure.com/text/analytics/v3.1/sentiment?'

urlParameters = {
    # Request parameters
    'opinionMining':'false'
}

#Load Azure Subscription Key
load_dotenv("AzureKey.env")
AzureKey = os.environ.get('AzureSubsKey')

urlHeaders = {
# Request headers
'Content-Type': 'application/json',
'Ocp-Apim-Subscription-Key': AzureKey,
}

    
#JSON required by Azure Resource, including text to be analized and language source
jsonRequired = {"documents":[{"id":"documentId","text":userText,"language":sourceLanguage}]}

# API Call
r = requests.post(sentimentAnalysesEndPoint, headers=urlHeaders, params=urlParameters, json=jsonRequired)

if (r.status_code !=200):
    status_code = str (r.status_code)
    return 'Not possible to process the API Call: '+status_code
    
else:
    try:
        sentimentAnalysesResponse = json.loads(r.text)
        sentimentAnalysesOutput = {}
        sentimentAnalysesMixOuput = []
        for i in sentimentAnalysesResponse['documents'][0]['sentences']:
            sentimentAnalysesOutput ['sentiment'] = i['sentiment']
            sentimentAnalysesOutput ['confidenceScores'] = i['confidenceScores']
            sentimentAnalysesOutput ['text'] = i['text'] 
            sentimentAnalysesMixOuput.append(sentimentAnalysesOutput) 
    
           
    except:
        None

return {'sentimentListOutput': sentimentAnalysesMixOuput, 'returnCode':0}

I am totally blocked so any help on how to fix/throubleshoot it will be very welcome

Thanks and Regards,
Danilo R. Alexandre

Please, format your post properly if you want to make sure we can understand your code without the markdown filter changing it

Regarding the issue, I noticed you installed python3-pip in the image, but python3-pip is already installed by default. On the other hand, you installed python-dev which is for Python 2.7, so you installed Python 2.7 as a dependncy and you don’t have the dev package for Python 3. You should use install python3-dev instead.

If you want to see stopped containers, you need to use docker ps -a

I strongly recommend to try everything in an interactive shell in a container before building the image so you can find issues before that.

Thanks Akos for the tips regarding formatting the text!!

With regards to your comments, I have changed the dockerfile as you proposed but the issue is still persist

Dockerfile

FROM python:3

RUN apt-get update -y && \
  apt-get install -y python3-pip python3-dev

WORKDIR /app

RUN pip install Flask requests python-dotenv

COPY . .

EXPOSE 5000

CMD ["python", "./sent_analisys.py"]

Image Build

Danilo.alexandre@RO-DALEXAND-10 MINGW64 ~/OneDrive - Nuance/Nuance/Udemy/Docker/azure_aci/flask
$ docker build -t analysis_sentiment .
[+] Building 17.9s (10/10) FINISHED
 => [internal] load build definition from Dockerfile                                                                                                      0.1s 
 => => transferring dockerfile: 259B                                                                                                                      0.0s 
 => [internal] load .dockerignore                                                                                                                         0.0s 
 => => transferring context: 2B                                                                                                                           0.0s 
 => [internal] load metadata for docker.io/library/python:3                                                                                               5.3s 
 => [internal] load build context                                                                                                                         0.0s 
 => => transferring context: 367B                                                                                                                         0.0s 
 => CACHED [1/5] FROM docker.io/library/python:3@sha256:e9c35537103a2801a30b15a77d4a56b35532c964489b125ec1ff24f3d5b53409                                  0.0s 
 => [2/5] RUN apt-get update -y &&   apt-get install -y python3-pip python3-dev                                                                           8.1s 
 => [3/5] WORKDIR /app                                                                                                                                    0.0s 
 => [4/5] RUN pip install Flask requests python-dotenv                                                                                                    3.9s 
 => [5/5] COPY . .                                                                                                                                        0.0s 
 => exporting to image                                                                                                                                    0.4s 
 => => exporting layers                                                                                                                                   0.3s 
 => => writing image sha256:af40628a51316af3d70b5f072556ea298a059829b3ab3cb1917f594ad8fea865                                                              0.0s 
 => => naming to docker.io/library/analysis_sentiment                                                                                                     0.0s 

Use 'docker scan' to run Snyk tests against images to find vulnerabilities and learn how to fix them

danilo.alexandre@RO-DALEXAND-10 MINGW64 ~/OneDrive - Nuance/Nuance/Udemy/Docker/azure_aci/flask
$

Image Details

danilo.alexandre@RO-DALEXAND-10 MINGW64 ~/OneDrive - Nuance/Nuance/Udemy/Docker/azure_aci/flask
$ docker image ls
    REPOSITORY                  TAG             IMAGE ID       CREATED             SIZE
    analysis_sentiment          latest          af40628a5131   11 minutes ago      991MB

Tried to run in interactive mode but no error has been shown

danilo.alexandre@RO-DALEXAND-10 MINGW64 ~/OneDrive - Nuance/Nuance/Udemy/Docker/azure_aci/flask
$ docker run -it analysis_sentiment

danilo.alexandre@RO-DALEXAND-10 MINGW64 ~/OneDrive - Nuance/Nuance/Udemy/Docker/azure_aci/flask

Container with Exited status

danilo.alexandre@RO-DALEXAND-10 MINGW64 ~/OneDrive - Nuance/Nuance/Udemy/Docker/azure_aci/flask
$ docker ps -a
CONTAINER ID   IMAGE                COMMAND                  CREATED         STATUS                     PORTS                  NAMES
25fce11b999f   analysis_sentiment   "python ./sent_anali…"   7 minutes ago   Exited (0) 7 minutes ago                          kind_wright

No logs available

danilo.alexandre@RO-DALEXAND-10 MINGW64 ~/OneDrive - Nuance/Nuance/Udemy/Docker/azure_aci/flask
$ docker logs 25fce11b999f

danilo.alexandre@RO-DALEXAND-10 MINGW64 ~/OneDrive - Nuance/Nuance/Udemy/Docker/azure_aci/flask
$

python file (well formatted now)

from flask import Flask
from flask import request
import json
import requests              
  
app = Flask(__name__)

 @app.route('/sentimentAnalysis', methods=['GET','POST'])
 def sentiment_analysis():

#Gets the input json from the Mix request
try:
    userText = ''
    sourceLanguage = ''
    mixContent = request.get_json(force=True)
    userText = mixContent['userText']
    sourceLanguage = mixContent['sourceLanguage']
    print('teste')        
except:
    None, print ("stopped here")

#Azure API EndPoint
sentimentAnalysesEndPoint = 'https://testing-language-service.cognitiveservices.azure.com/text/analytics/v3.1/sentiment?'

urlParameters = {
    # Request parameters
    'opinionMining':'false'
}

#Load Azure Subscription Key
#load_dotenv("AzureKey.env")
#AzureKey = os.environ.get('AzureSubsKey')

urlHeaders = {
# Request headers
'Content-Type': 'application/json',
'Ocp-Apim-Subscription-Key': "<Key>",
}

    
#JSON required by Azure Resource, including text to be analized and language source
jsonRequired = {"documents":[{"id":"documentId","text":userText,"language":sourceLanguage}]}

# API Call
r = requests.post(sentimentAnalysesEndPoint, headers=urlHeaders, params=urlParameters, json=jsonRequired)

if (r.status_code !=200):
    status_code = str (r.status_code)
    return 'Not possible to process the API Call: '+status_code
    
else:
    try:
        sentimentAnalysesResponse = json.loads(r.text)
        sentimentAnalysesOutput = {}
        sentimentAnalysesMixOuput = []
        for i in sentimentAnalysesResponse['documents'][0]['sentences']:
            sentimentAnalysesOutput ['sentiment'] = i['sentiment']
            sentimentAnalysesOutput ['confidenceScores'] = i['confidenceScores']
            sentimentAnalysesOutput ['text'] = i['text'] 
            sentimentAnalysesMixOuput.append(sentimentAnalysesOutput) 
    
           
    except:
        None

return {'sentimentListOutput': sentimentAnalysesMixOuput, 'returnCode':0}

I meant “interactive shell”. It looks like you just started a container from the built image using its own command instead of a shell.

docker run -it python:3 bash

Now you can run the commands interactively that you want to use in your Dockerfile. If you have an issue, you don’t need deal with a stopped container. You can see files in the container or find out what is missing, try to install it and run the command again.

Since the exit code is 0, it means the python code ran without throwing any error. It may be because there is a condition which was not met and the python code just didn’t do anything or something else happened, but the point is that you need to debug your code.

An other reason to believe your code did not run at all.
In your python code you have a try catch block at the and without handling the exception. Make sure you always handle specific exceptions even if you don’t want to show an error message because you expect it. Otherwise you can miss important exceptions that you did not expect.

If you would like to have more debugging tips, you can find my presentation about it on Docker’s YouTube channel.

I added the GitHub link as a comment but it was not accepted so here it is:

I mention cases when you don’t have error message and I talk about working with interactive shells in containers.

Thanks for these valuable tips on troubleshooting!

In my case, I have fixed by adding the following piece of code to my application.

Code

if __name__ == "__main__":
app.run(host="0.0.0.0", debug=True, port="5000")