Search code examples
dockerdockerfiletouch

Touch command is not affecting Docker image


I'm trying to create a basic test file inside Docker image like below;

FROM alpine as build

RUN cd /opt/bin/ && touch test123
CMD echo "Hello world" 


EXPOSE 9005
EXPOSE 9006

So image is successfully creating. But when I login to the image after deploy to the local Kubernetes, "kubectl exec -it", I do not see this "test123" file in the image.

Also I added "ADD /tmp/test/ /opt/" command, but this is also gives erro like below. Even /tmp/test directory exist on the server and there are couple of files exist.

Step 3/8 : ADD /tmp/test/ /opt/
ADD failed: file not found in build context or excluded by .dockerignore: stat tmp/test/: file does not exist
Build step 'Execute shell' marked build as failure
Finished: FAILURE

Any idea? Thanks!


Solution

  • From the description it seems that you were skipping various steps and you ignored the fact that the container will stop after the command has been executed. After the container has stopped, K8 tries to restart it without any success, because the command will finish and stop the container again. Also, I think kubectl is not good for such use cases, but you might have your reasons so I leave it there.

    Taking into account the fact that you are using kubectl, I have made an working example

    FROM alpine as build
    RUN cd /bin && touch test123
    CMD echo "Hello world" && sleep 6000
    EXPOSE 9005
    EXPOSE 9006
    

    Changes:

    1. The path to /bin folder was incorrect. So I fixed it.
    2. To avoid the container from stopping, I added sleep command to keep it up.

    Put this Dockerfile into a separate folder and then in that folder run

    docker build -t hello_world:1.0 .
    

    This will build the image with name hello_world:1.0. Then start the K8 cluster

    kubectl run hello --image=hello_world:1.0
    

    Now you will have the pod named 'hello' and corresponding containers, where you can exec into. To exec into a container, run:

    kubectl exec -i --tty hello -- /bin/sh
    

    This will start an interactive shell session inside the container. There you can see your file as well if you run

    ls /bin
    

    Here is the documentation for further information.

    I hope that the example helps you with your issue.