skip to Main Content

Dockerfile:

FROM ubuntu:latest
ARG DEBIAN_FRONTEND=nointerative
WORKDIR /var/photogram
COPY . .
RUN chmod +x /var/photogram/install.sh
CMD /var/photogram/install.sh

install.sh:

#!/bin/bash

echo "hello world"
touch hello.txt
touch sad.txt

Structure of files:

Tholkappiar2003@docker:~/docker$ tree
.
├── Dockerfile
└── install.sh

1 directory, 2 files

Docker Build: docker build -t photo:local .

Docker Run: docker run -it photo:local bash

No Errors and nothing.

After running the container:

root@8dbd47fa58e3:/var/photogram# ls
Dockerfile  install.sh

I can run the script inside the Docker image which gives the output but it should be done when starting the container automatically.

There is no hello.txt file or sad.txt file which would be created by the install.sh script.

The commands in install.sh should be executed when running the container.

2

Answers


  1. You are overwriting the CMD you defined in your Dockerfile. So if you want to execute the script when the container starts, then use:

    $ docker run photo:local
    hello world
    

    If instead you want to execute the script whenever you open a bash session, then place the script in ~/.bashrc:

    FROM ubuntu:latest
    ARG DEBIAN_FRONTEND=nointerative
    WORKDIR /var/photogram
    COPY . .
    RUN chmod +x /var/photogram/install.sh && 
        echo "/var/photogram/install.sh" > ~/.bashrc
    
    $ docker build -t photo:local .
    $ docker run -it photo:local
    hello world
    root@157dbbb711d4:/var/photogram# ls
    Dockerfile  hello.txt  install.sh  sad.txt
    
    Login or Signup to reply.
  2. This is because in the Dockerfile you use a CMD and when you start a new container, you specified the bash command which automatically replaces your CMD. On the other hand, if you want the script to be executed when creating a new container, put ENTRYPOINT instead.

    FROM ubuntu:latest
    ARG DEBIAN_FRONTEND=nointerative
    WORKDIR /var/photogram
    COPY . .
    RUN chmod +x /var/photogram/install.sh
    ENTRYPOINT ["/var/photogram/install.sh"]
    

    Run new container:

    docker run -it photo:local
    hello world
    

    This will cause the script to be executed but you will no longer be able to connect in bash unless you enter another ENTRYPOINT

    Run container and connect shell:

    docker run -it --entrypoint bash photo:local
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search