Docker: First steps
The main goal of this note is show some basic commands to start using docker. To deep learning about docker check the following links:
- Install docker: https://docs.docker.com/get-docker/
- Docker documentation: https://docs.docker.com/
- Why docker: https://docker.com/why-docker
Commands
Ok, letβs check if we have any container running:
docker ps
docker ps
: List all running containersdocker ps -a
: List all containers (running and stopped)
We also can list all docker images:
docker image
docker image ls
: List all imagesdocker 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 containerbash
: 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 containernode /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!"