Run a container:
docker run ruby:2.7
# run and open bash shell
# --rm will remove the container when done instead of keeping it around
# you can clear any lingering containers with a `docker system prune`
docker run -it --rm ruby:2.7 bash
# mount files onto the container (updates to local files will reflect on the container)
docker run -it --rm -v $PWD:/app ruby:2.7 bash
# map port from container to host
docker run -it --rm -p 4567:4567 -v $PWD:/app ruby:2.7 bash
Check on running containers:
# list running container
docker ps
# check resource utilization of running containers
docker stats
# connect to a running container
docker exec -it <image-name-or-id> bash
Orchestrating with docker-compose:
NOTE: all docker-compose commands need to be run in a directory that has a docker-compose.yml
file (or pass the -f
flag)
# build all services
docker-compose build
# build a specific service's container
docker-compose build <service-name>
# start and stop services
docker-compose start
docker-compose stop
# create / remove services (will do the start/stop; prefer these if you want to get a clean slate)
# up will build if containers have not been built before, run docker-compose build if you need to rebuild
docker-compose up
docker-compose down
# restart all services or a particular service
docker-compose restart
docker-compose restart <service-name>
# list running container that are orchestrated by just this compose file
docker-compose ps
# get logs (stdout & stderr) from all containers
docker-compose logs
Ruby web app (web.rb
):
require 'sinatra'
require 'redis'
get '/hello/:name?' do
"Hello #{params["name"]}!"
end
get '/count' do
redis = Redis.new(host: "redis")
redis.incr("count")
puts "#{redis.get("count")}"
"#{redis.get("count")}"
end
Dockerfile
for building a container image:
FROM ruby:2.7
RUN gem install sinatra redis
WORKDIR /app
COPY . .
CMD ["ruby", "web.rb", "-o", "0.0.0.0"]
Config for spinning up the ruby container image & redis using docker-compose.yml
version: '3'
services:
web:
build: ./
ports:
- "4567:4567"
volumes:
- ${PWD}:/app
redis:
image: "redis:5"
Place all 3 files in a directory and run:
docker-compose up
This will pull down the necessary images (ruby & redis), build the web container and start the web and redis services. If all goes well, the ruby app should be accessible at 4567 on your host machine:
https://localhost:4567/hello/:name and https://localhost:4567/count
Try this at the terminal (or open the urls in a browser):
At the terminal
curl -i 'https://localhost:4567/hello/world'
curl -i 'https://localhost:4567/hello/abc'
curl -i 'https://localhost:4567/count'