Docker Basics: Docker Compose

Create, configure, and run a multi-container application using Docker Compose and this introductory tutorial.

Docker Compose is a tool that allows you to run multi-container applications. With compose we can use yaml files to configure our application’ services and then using a single command to create and start all of the configured services. I use this tool a lot when it comes to local development in a microservice environment. It is also lightweight and needs just a small effort. Instead of managing how to run each service while developing, you can have the environment and services needed preconfigured and focus on the service that you currently develop.

With docker compose , we can configure a network for our services, volumes, mount-points, environmental variables — just about everything.

To showcase this we are going to solve a problem. Our goal would be to extract data from MongoDB using Grafana. Grafana does not have out-of-the-box support for MongoD, therefore,e we will have to use a plugin.

The first step is to create our networks. Creating a network is not necessary since your services, once started, will join the default network. We will make a showcase of using custom networks, and have a network for backend services and a network for frontend services. Apparently, network configuration can get more advanced and specify custom network drivers or even configure static addresses.

version: '3.5'

networks:
  frontend:
    name: frontend-network
  backend:
    name: backend-network
    internal: true


The backend network is going to be internal so there won’t be any outbound connectivity to the containers attached to it.

Then we will setup our MongoDB instance.

version: '3.5'

services:
  mongo:
    image: mongo
    restart: always
    environment:
      MONGO_INITDB_ROOT_USERNAME: ${MONGO_USER}
      MONGO_INITDB_ROOT_PASSWORD: ${MONGO_PASSWORD}
    volumes:
      - ${DB_PATH}:/data/db
    networks:
      - backend


As you see, we specified a volume. Volumes can also be specified separately and attached to a service. We used environmental variables for the root account, and you might also have noticed that the password is going to be provided through environmental variables. The same applies for the volume path, too. You can have a more advanced configuration for volumes in your compose configuration and reference them from your service.

Our next goal is to set up the proxy server which will be in the middle of our Grafana and MongoDB server. Since it needs a custom Dockerfile to create it, we will do it through docker-compose. Compose has the capability to spin up a service by specifying the docker file.

So let’s start with the Dockerfile.

FROM node

WORKDIR /usr/src/mongografanaproxy

COPY . /usr/src/mongografanaproxy

EXPOSE 3333

RUN cd /usr/src/mongografanaproxy
RUN npm install
ENTRYPOINT ["npm","run","server"]

Then let’s add it to compose.

version: '3.5'

services:
  mongo-proxy:
    build:
      context: .
      dockerfile: ProxyDockerfile
    restart: always
    networks:
      - backend


And the same will be done to the Grafana image that we want to use. Instead of using a ready Grafana image, we will create one with the plugin preinstalled.

FROM grafana/grafana

COPY . /var/lib/grafana/plugins/mongodb-grafana

EXPOSE 3000

version: '3.5'

services:
  grafana:
    build:
      context: .
      dockerfile: GrafanaDockerfile
    restart: always
    ports:
      - 3000:3000
    networks:
      - backend
      - frontend


Let’s wrap them all together:

version: '3.5'

services:
  mongo:
    image: mongo
    restart: always
    environment:
      MONGO_INITDB_ROOT_USERNAME: ${MONGO_USER}
      MONGO_INITDB_ROOT_PASSWORD: ${MONGO_PASSWORD}
    volumes:
      - ${DB_PATH}:/data/db
    networks:
      - backend
  mongo-proxy:
    build:
      context: .
      dockerfile: ProxyDockerfile
    restart: always
    networks:
      - backend
  grafana:
    build:
      context: .
      dockerfile: GrafanaDockerfile
    restart: always
    ports:
      - 3000:3000
    networks:
      - backend
      - frontend
networks:
  frontend:
    name: frontend-network
  backend:
    name: backend-network
    internal: true


So let’s run them all together.

docker-compose -f stack.yaml build
MONGO_USER=root MONGO_PASSWORD=root DB_PATH=~/grafana-mongo  docker-compose -f stack.yaml up


This code can be found on Github, and for more, check out the Docker ImagesDocker Containers, and Docker registry posts.

Originally published by Emmanouil Gkatziouras at https://dzone.com

Learn more

Jenkins, From Zero To Hero: Become a DevOps Jenkins Master

☞ http://school.learn4startup.com/p/rIKN0OqT2

Docker Mastery: The Complete Toolset From a Docker Captain

☞ http://school.learn4startup.com/p/r18lJJ_1Te

Docker and Kubernetes: The Complete Guide

☞ http://school.learn4startup.com/p/7bXEiVS7Q

Docker Crash Course for busy DevOps and Developers

☞ http://school.learn4startup.com/p/Sy8T4CfkM

Selenium WebDriver with Docker

☞ http://school.learn4startup.com/p/9fGLIrlWl

Amazon EKS Starter: Docker on AWS EKS with Kubernetes

☞ http://school.learn4startup.com/p/TpIgI9KEN

#docker

What is GEEK

Buddha Community

Docker Basics: Docker Compose
Iliana  Welch

Iliana Welch

1595249460

Docker Explained: Docker Architecture | Docker Registries

Following the second video about Docker basics, in this video, I explain Docker architecture and explain the different building blocks of the docker engine; docker client, API, Docker Daemon. I also explain what a docker registry is and I finish the video with a demo explaining and illustrating how to use Docker hub

In this video lesson you will learn:

  • What is Docker Host
  • What is Docker Engine
  • Learn about Docker Architecture
  • Learn about Docker client and Docker Daemon
  • Docker Hub and Registries
  • Simple demo to understand using images from registries

#docker #docker hub #docker host #docker engine #docker architecture #api

August  Murray

August Murray

1615008840

Top 24 Docker Commands Explained with Examples

In my previous blog post, I have explained in detail how you can Install Docker and Docker-compose on Ubuntu

In this guide, I have explained the Top 24 Docker Commands with examples.

Make sure you have sudo or root privileges to the system.

Docker Commands

  1. The command to check the version of Docker installed.
  2. To look/search for available docker images from the Docker registry.
  3. To pull docker images from the Docker registry.
  4. Listing all the docker images
  5. Creating / Running docker container from Docker image.
  6. To list the actively running docker containers.
  7. To list all the docker containers
  8. To stop a Container
  9. To start a Container
  10. To restart a Docker container
  11. To login to running Docker container
  12. To delete the stopped Docker containers
  13. To delete Docker images from the Local system
  14. To check logs of a running Docker container
  15. Killing docker containers
  16. Log in to Docker Hub registry (hub.docker.com)
  17. Removing docker hub registry login from the system.
  18. Check active resource usage by each containers
  19. Rename a Docker container
  20. To display system wide information of Docker
  21. Inspecting a Docker container
  22. Building docker images from Docker file
  23. Creating new docker images from a Container
  24. Pushing Docker images from Local to Docker registry.

#docker #docker-command #containers #docker-compose #docker-image

Loma  Baumbach

Loma Baumbach

1600358785

Deploy a Tomcat Application Using Docker-Compose

In this blog, we will learn what is docker-compose and how we can deploy a tomcat application which uses mysql database. We will learn how we can setup a development environment using docker-compose in a single command

Prerequisite:

  1. Docker and Docker-compose installed

INTRODUCTION

  • Docker-compose is a tool which is used to deploy multi-container application.
  • One single yaml file to deploy your application on the server.
  • Best suited for the developers to setup their workstation in a single command without installing any kind of dependencies for the application
  • docker-compose up to start your application
  • docker-compose down to clean up all the docker containers

Let’s take an example here:

We have a project called user registration which uses mysql for storing the data . In terms of microservices, we can say that we have two services as shown below:

  • Web Service
  • Database Service

You can clone this git repo and try the below example

Explanation of docker-compose

  1. **version : **This is the version as per the docker engine you have installed on your machine
  2. **services: **This is the main tag which is used to configure multiple services and under that we have details of all the services

3. web: This is our service name -> using image, ports and volumes

4. **volumes: **To store the database files

Now we will create main docker-compose file which will together launch a tomcat, mysql and phpmyadmin container

Tomcat container — To run your application

**Database container **— To store the data

PhpMyAdmin — Access the database through GUI

So we will have three services

  1. db — we are using local path to store the data so that when you run docker-compose down all your data will retain. If you use the volume then all data will get lost if you run the docker-compose down

Also, we are importing sql file so that our database is ready with the sample data. It is good so that each developer will always have the base or the actual data to run their application on the local machine

2. phpmyadmin — which is used to access the database through GUI and it depends on service db

3. web — which is used to access your web application and it also depends on service db

version: '3.3'
services:
   db:
     image: mysql:5.7
     volumes:
       - /opt/test:/var/lib/mysql
       - ./mysql-dump:/docker-entrypoint-initdb.d
     environment:
       MYSQL_ROOT_PASSWORD: root
       MYSQL_DATABASE: testdb1
       MYSQL_USER: testuser
       MYSQL_PASSWORD: root
     ports:
       - 3306:3306
phpmyadmin:
    depends_on:
      - db
    image: phpmyadmin/phpmyadmin
    ports:
      - '8081:80'
    environment:
      PMA_HOST: db
      MYSQL_ROOT_PASSWORD: root
web:
    depends_on:
      - db
    image: tomcat
    volumes:
      - ./target/LoginWebApp-1.war:/usr/local/tomcat/webapps/LoginWebApp-1.war
    ports:
      - '8082:8080'
    environment:
      MYSQL_ROOT_PASSWORD: root
      MYSQL_DATABASE: testdb1
      MYSQL_USER: testuser
      MYSQL_PASSWORD: root

#docker-compose #docker-image #docker

Cómo instalar Drupal con Docker Compose

Введение

Docker позволяет легко помещать приложения и службы в контейнеры, чтобы их можно было запускать где угодно. Однако при работе с Docker можно легко накопить чрезмерное количество неиспользуемых образов, контейнеров и томов данных, замедляющих работу и потребляющих место на диске.

Docker предоставляет все необходимые инструменты для очистки системы из командной строки. В этом руководстве с полезными советами кратко описываются полезные команды для освобождения места на диске и организации системы посредством удаления неиспользуемых образов, контейнеров и томов Docker.

Использование этого руководства:

  • Это руководство в формате полезных советов содержит автономные сниппеты для командной строки
  • Вы можете перейти к любому разделу, актуальному для задачи, которую вы пытаетесь выполнить.

Синтаксис замены команды command $(``command``), используемый в командах, доступен во многих популярных оболочках, включая bash, zsh и Windows Powershell.

Очистка всех неиспользуемых или не связанных с контейнерами образов, контейнеров, томов и сетей

В Docker имеется команда, очищающая все не связанные с контейнерами ресурсы, в том числе образы, контейнеры, тома и сети:

docker system prune

Чтобы удалить все остановленные контейнеры и неиспользуемые образы (а не только образы, не связанные с контейнерами), добавьте в эту команду флаг -a:

docker system prune -a

Удаление образов Docker

Удаление одного или нескольких конкретных образов

Используйте команду docker images с флагом -a, чтобы найти идентификатор удаляемых образов. Эта команда покажет вам все образы, включая промежуточные слои образов. Когда вы определитесь с составом удаляемых образов, вы можете передать их идентификаторы или теги в docker rmi:

Список:

docker images -a

Удаление:

docker rmi Image Image

Удаление образов, не привязанных к контейнеру

Образы Docker состоят из нескольких слоев. Несвязанные образы — это слои, не имеющие связей с каким-либо образами с тегами. У них нет никакого назначения, и они просто занимают место на диске. Их можно найти, добавив флаг фильтра -f со значением dangling=true в команду docker images. Если вы уверены, что хотите удалить их, вы можете использовать команду docker images purge:

#drupal #docker #docker compose #docker images

Haylie  Conn

Haylie Conn

1623316050

Volume Management, Compose v2, Skipping Updates, and more in Docker Desktop 3.4

We are excited to announce the release of Docker Desktop 3.4.

This release includes several improvements to Docker Desktop, including our new Volume Management interface, the Compose v2 roll-out, and changes to how to Skip an update to Docker Desktop based on your feedback.

Volume Management

Have you wanted a way to more easily manage and explore your volumes?

In this release we’re introducing a new capability in Docker Desktop that helps you to create and delete volumes from Desktop’s Dashboard as well as to see which ones are In Use.

#products #docker #docker compose #docker desktop