Docker: First steps

Carlos Costa

The main goal of this note is show some basic commands to start using docker. To deep learning about docker check the following links:

Commands


Ok, let’s check if we have any container running:

docker ps
  • docker ps: List all running containers
  • docker ps -a: List all containers (running and stopped)

We also can list all docker images:

docker image
  • docker image ls: List all images
  • docker image rm <image_id>: Remove an image

Now we will install and image to next steps:

docker pull node
  • docker pull <image_name>: Download an image

So we run a container with this image:

docker run -it node bash

πŸ‘‡

root@599b8feda630:/# node --version
v20.5.1
  • docker run <image_name>: Run a container with an image
  • -it: Interactive mode, we can use the terminal inside the container
  • bash: Run bash inside the container

Ok, let’s do something using nodejs, we will share a volume with our local machine, and execute a script inside the container:

first, create a file main.js with this content:

πŸ“‚ app\
  πŸ“„ main.js
function fn() {
  console.log('Hello world')
}
fn()

inside app folder we will create this command:

docker run -it --volume .:/app --name learn node node /app/main.js
πŸ‘‡
# Hello world
  • --volume .:/app: Share the current folder with the container
  • --name learn: Set a name to the container
  • node /app/main.js: Execute a script inside the container

now we will do something more complex, we will run a web server inside the container, sharing a port and accessing from our local machine:

write this code inside main.js:

var http = require('http')
var server = http.createServer(function (req, res) {
  res.writeHead(200, { 'Content-Type': 'text/plain' })
  res.end('Hello World\n')
})
server.listen(3000, () =>
  console.log('Server running at http://localhost:3000/')
)

Running docker command:

docker run -dit --volume .:/app --name learn -p 3000:3000 node node /app/main.js
πŸ‘‡
# Server running at http://localhost:3000/
  • -p 3000:3000: Share the port 3000 from container to local machine
  • -d: Run the container in background

πŸ‹ run, start, exec, stop


let’s understand the difference between these commands.

Creating a container:

docker run -dit --name learn node

Execute a command inside the container:

docker exec learn node --version

Stop container:

docker stop learn

Start again and run a command:

docker start learn
docker exec learn echo "hello world!"

Resources: