Tuesday, July 23, 2019

Docker Images & Dockerfile

  1. creating new image - can be done when you can't find needed container image on the docker-hub.
  2. Dockerfile:
    1. text file written in a specific format a docker can understand
    2. Every line starts with instruction (FROM, RUN, COPY etc.) followed by argument
    3. Each instruction instructs docker to do a specific action
      1. First line starts with a base OS or another image: FROM centos
      2. Then you install needed dependencies, for example:
        1. RUN yum update -y && yum install python python-pip
        2. RUN pip install flask flask-mysql
      3. Copy source files from docker-host to the docker-image:
        1. COPY . /opt/source-code
      4. Command to run when image is run as a container:
        1. ENTRYPOINT FLASK_APP=/opt/source-code/app.py flask run
    4. When building docker image, every line of Dockerfile creates layer of the docker image:
      1. For the above example layers are:
        1. layer 1: Base CentOS layer
        2. layer 2: changes in yum packages
        3. layer 3: changes in pip packages
        4. layer 4: source code
        5. layer 5: update entry-point with "flask" command
      2. docker build:
        1. docker build Dockerfile -t nameOfTheImage
        2. docker build -t nameOfTheImage dockerFileDirectoryName
        3. docker build -t nameOfTheImage .
        4. docker build Dockerfile -t nameOfTheImage .
      3. to view build process history: docker history imageName
      4. layered build process helps to debug and also helps to start build process, in case of failure, from the needed layer (this is done automatically using docker cash). The same is true when you want to add additional steps in dockerfile, rebuild will be done using cash, so only affected layers will be rebuilt
    5. CMD vs ENTRYPOINT:
      1. CMD defines command and it's parameters (if any) which will run when container starts:
        1. CMD ["mysqld"] or CMD mysqld
        2. CMD ["sleep", "5"] or CMD sleep 5
      2. ENTRYPOINT is like CMD but also appends any input to the "docker run" to the end of the command as parameter:
        1. ENTRYPOINT ["sleep"] or ENTRYPOINT sleep
        2. docker run centos-sleeper 10 # 10 will be appended as parameter to the "sleep" command
        3. when you append some input to the "docker run" and use CMD, then this is not appended to the command following CMD - the entire appended input is used as command after CMD 
      3. To use some value as default value for the ENTRYPOINT:
        1. ENTRYPOINT sleep
        2. CMD 10
        3. two lines above will be "sleep 10" by default, so CMD is appended to the ENTRYPOINT as parameter 

No comments:

Post a Comment