Lab #19: Exec Command

In this lab we are going to look into docker-compose exec command. Docker exec is used to run commands in a running container, similarly docker-compose exec runs commands in your services.

Command instructions

Exec

docker-compose exec [options] [-e key=val...] service command [args...]

Run commands in your services. Commands are by default allocating a TTY.

Options include:
-T disables pseudo-tty allocation.
--index=index specifies container when there are multiple instances of a service

Tested Infrastructure

Platform Number of Instance Reading Time
Play with Docker 1 5 min

Pre-requisite

Setup enviroment

$ mkdir app
$ cd app

Create a docker-compose.yml file

version: '3.1'
services:
  #Webservers
   webserver:
     image: nginx:alpine
     restart: unless-stopped
     expose:
       - "80"
       - "443"
  #Load Balancer
   loadbalancer:
     image: nginx:alpine
     volumes:
       - ./nginx.conf:/etc/nginx/nginx.conf:ro
     depends_on:
       - webserver
     ports:
       - "80:4000"

Create a nginx.conf file

user  nginx;
events {
    worker_connections   1024;
}
http {
        server {
              listen 4000;
              location / {
                proxy_pass http://webserver:80;
              }
        }
}

Note: This file will configure our load balancer.

Create the compose containers

$ docker-compose up -d --scale webserver=3

View the containers

$ docker-compose ps

Execute commands in different webservers

$ docker-compose exec --index=1 webserver  sh -c "echo 'Welcome to webserver1' > /usr/share/nginx/html/index.html"
$ docker-compose exec --index=2 webserver  sh -c "echo 'This is webserver2' > /usr/share/nginx/html/index.html"
$ docker-compose exec --index=3 webserver  sh -c "echo 'Webserver3 is up' > /usr/share/nginx/html/index.html"

Verify changes

$ curl http://localhost

Note: In order to verify all changes we’ll have to use the curl command multiple times.

Contributor

Om Anand

Lab #20: Kill Command