Search code examples
dockerdockerfile

My application has started twice when i'm bringing up my container


I wrote a small c program(asks for user's name and prints 'welcome name') and a dockerfile to copy the program inside a container and execute it. I created the container and it exited after showing 'welcome name'. But after that whenever I'm starting the container, I can see 2 instances of my program running. I'm unable to understand why?

My small application(myapp.c) for proof of concept, it looks like this -

#include <stdio.h>
#include <string.h>
int main()
{
char name[30] = {0};
printf("Enter your name: ");
gets(name);
printf("welcome ");
puts(name);
return 1;
} 

I've created a dockerfile to create an image which will run this application. My dockerfile looks like this -

FROM ubuntu:latest
RUN apt-get update && apt-get -y install gcc
RUN mkdir /home/app/
#copy myapp.c in container
COPY . /home/app/
WORKDIR /home/app/
RUN ["gcc", "myapp.c", "-o", "myapp"]
CMD ./myapp 

After that I'm executing -

agangopadhyay@IN-RebhCTmbk5xO:~/docker/myapp$ docker build -t myappimage:1.0 .
agangopadhyay@IN-RebhCTmbk5xO:~/docker/myapp$ docker run -it --name mycontainer myappimage:1.0
Enter your name: Amiya
welcome Amiya           

Then the container exits as I think the main program exited.

agangopadhyay@IN-RebhCTmbk5xO:~/docker/myapp$ docker ps -a
CONTAINER ID   IMAGE            COMMAND                CREATED             STATUS       PORTS              NAMES
7e5b2a491353   myappimage:1.0   "/bin/sh -c ./myapp"   About an hour ago   Exited (137) 10 seconds ago mycontainer

But when I'm restarting the container using -

agangopadhyay@IN-RebhCTmbk5xO:~/docker/myapp$ docker start mycontainer
mycontainer
agangopadhyay@IN-RebhCTmbk5xO:~/docker/myapp$ docker exec -it mycontainer /bin/bash
root@7e5b2a491353:/home/app# ps -axu | grep myapp
root         1  0.1  0.0   2800  1168 pts/0    Ss+  14:04   0:00 /bin/sh -c ./myapp
root         7  0.0  0.0   2680  1072 pts/0    S+   14:04   0:00 ./myapp
root        17  0.0  0.0   3528  1684 pts/1    S+   14:04   0:00 grep --color=auto myapp

I can see 2 instances of myapp running. I wonder why? Any pointer will be helpful.


Solution

  • Your application is running once, the other process is a shell to launch your app. In this output:

    root@7e5b2a491353:/home/app# ps -axu | grep myapp
    root         1  0.1  0.0   2800  1168 pts/0    Ss+  14:04   0:00 /bin/sh -c ./myapp
    root         7  0.0  0.0   2680  1072 pts/0    S+   14:04   0:00 ./myapp
    

    Pid 1 is /bin/sh with the arguments -c and ./myapp. Your app is running as pid 7. If you want to eliminate the shell, you would switch to the exec syntax in the dockerfile:

    CMD [ "./myapp" ]