Post

Docker Cookbook

{% raw %}

  • List all images ?
    docker images
    • List all containers ?
    docker container ls -a / docker ps -a
    • List all containers belong to a particular image ?
    docker ps --all --filter ancestor=<image_name_or_id>
    • See all the envs passed to a container used during creating it. ?
    docker container inspect <container id>
    • Run the docker in detached mode
    docker run -d
    • Docker: publish port 5004 of container to 8000 of host
    docker run -p 8000:5004 <image>
    • See the logs of the docker when the docker runs in a detached mode ?
    docker logs -f <container-id>
    • Close the container by giving time to close all the operations inside it ?
    docker stop <container-id>
    • Kill all the container and all the operations inside the container ?
    docker container kill <container-id>
    • How do you see all the docker events happening in a system ?
    docker system events
    • See the statistics of a container
    docker stats <container-id>
    • How do you transmit stdin, stdout of the container to the terminal ?
    docker attach <container-id>
    • What to give as a additional parameter such that the previous step container is not stopped ?

    If the container started with -d or -i then Ctrl C

    Dockerfile for a simple flask/python application ?

    FROM python:3.8-slim-buster WORKDIR /backend ARG URL ENV ENVIRONMENT=""COPY ./service/requirements.txt /backend/service/requirements.txt RUN pip install --no-cache-dir --upgrade -r /backend/service/requirements.txt COPY ./service /backend/serviceEXPOSE 8080CMD ["uvicorn", "service.app:app", "--host", "0.0.0.0", "--port", "8080"]
    • Clean up
    docker kill $(docker ps -q)docker rm $(docker ps -a -q)docker rmi $(docker images -q)
    • Conditional Logic in Docker Build
    FROM node:alpineRUN mkdir -p /usr/src/appWORKDIR /usr/src/appCOPY package.json /usr/src/app/RUN npm installCOPY . /usr/src/appENV PORT 3000ARG DOCKER_ENVENV NODE_ENV=${DOCKER_ENV}RUN if [ "$DOCKER_ENV" = "stag" ] ; then  echo   your NODE_ENV for stage is $NODE_ENV;  \else  echo your NODE_ENV for dev is $NODE_ENV; \fi
    • when you build this Dockerfile with this command

    docker build –build-arg DOCKER_ENV=stag -t test-node . You will see at layer

    —> Running in a6231eca4d0b your NODE_ENV for stage is stag When you run this docker container and run this command your output will be

    /usr/src/app # echo $NODE_ENVstag

    {% endraw %}

    This post is licensed under CC BY 4.0 by the author.