How to configure a static IP address on Linux

In this tutorial, How to configure a static IP address on Linux. Step by step to make a static IP address on Linux.

Note: To change the network setting a good idea to make a copy of any configured file before your changes.

Configure a static IP address on Linux

For RHEL 8

How to configure a static IP address on an RHEL system. using command shown list network connections and devices on the system.

$ nmcli dev status

Now, To change the network interface from dynamic to static, you need to edit the file in folder “/etc//network-scripts”. In this example, I will create new file -Comtrend7FB9

Configuring a static IP address as below

HWADDR=7C:67:2A:CC:DF:8F
ESSID=Comtrend7FB9
MODE=Managed
KEY_MGMT=WPA-PSK
SECURITYMODE=open
MAC_ADDRESS_RANDOMIZATION=default
TYPE=Wireless
IPADDR=192.168.3.4  # Ip address static for Linux server
PROXY_METHOD=none
BROWSER_ONLY=no
BOOTPROTO=static      
DEFROUTE=yes
IPV4_FAILURE_FATAL=no
IPV6INIT=yes
IPV6_AUTOCONF=yes
IPV6_DEFROUTE=yes
IPV6_FAILURE_FATAL=no
IPV6_ADDR_GEN_MODE=stable-privacy
NAME=Comtrend7FB9
UUID=3f5a6317-27c7-249f-bfaa-1d2fa5283482
ONBOOT=yes

Restarting NetworkManager.

$ sudo systemctl restart NetworkManager

For Ubuntu 18.10

Using (network manager command-line interface) command to list the network interface on Ubuntu server.

$ nmcli d

For example, configure a static IP address on the Ubuntu system.

# interfaces(5) file used by ifup(8) and ifdown(8)
auto lo
iface lo inet loopback
auto enp0s25
iface enp0s25 inet static
    address 192.168.3.4
    netmask 255.255.255.0
    network 192.168.3.1
    broadcast 192.168.3.255

Restart the networking service.

$ sudo  systemctl restart NetworkManager.service

Configure Static IP On CentOS 6

You can update/edit as follow static IP configure. For example, I will update for eth0 interface network.

HWADDR=00:08:A2:0B:BA:B7
TYPE=Ethernet
BOOTPROTO=none
# IP static for Server #
IPADDR=192.168.3.4
# Subnet #
PREFIX=24
# Set default gateway IP for server #
GATEWAY=192.168.3.1
# Set dns servers #
DNS1=192.168.3.1
DNS2=8.8.8.8
DNS3=8.8.4.4
DEFROUTE=yes
IPV4_FAILURE_FATAL=no
# Disable ipv6 #
IPV6INIT=no
NAME=eth0
# This is system specific and can be created using 'uuidgen eth0' command #
UUID=31171a6f-bcg1-44de-8h6e-cf8e782f8bd6
DEVICE=eth0
ONBOOT=yes

Save and close the file. you need to restart the service network to apply the configure for the eth0 interface network.

$ sudo systemctl restart network

Conclusion

You have configure a static IP address on Linux. I hope will this your helpful. Thank you for reading the DevopsRoles page!

Bash script Create dir and copy specific files

In this tutorial, I will share the bash script Create dir and copy specific files while changing the in Linux.

My example

path_to_files variable structure folder as below

[root@localhost ~]# tree /home/huupv/
/home/huupv/
├── devopsroles.txt
├── dir
│   └── test.csv
└── huuphan.txt

1 directory, 3 files

dir_names variable will new folder after running bash script as below

[root@localhost ~]# tree folder
folder
├── folder-devopsroles.txt
├── folder-dir
│   └── test.csv
└── folder-huuphan.txt

1 directory, 3 files

Bash script Create dir and copy specific files and change name files/folder.

#!/bin/bash
dir_names=$1
path_to_files='/home/huupv/'

if [ ! -d $path_to_files ]; then
        echo "$path_to_files not found folder";
        exit 1;
fi

if [ -d $dir_names ]; then
        echo "$dir_names is exists";
        exit 1;
fi


echo "Creating $i and copying over files..."
mkdir $dir_names
for i in $(ls $path_to_files); do
    cp -rf ${path_to_files}${i} ${dir_names}/${dir_names}-$i
done

The result after run Bash Script

Thank you for reading the DevopsRoles page!

Get permission of chmod as numerical value on Linux

chmod command is used to change the permissions of files or directories. In this tutorial, I will get of as value on Linux.

For example, Check Linux file and folder permissions with the ls command as below

[vagrant@app1 ~]$ ls -l /home/vagrant/*
-rw-rw-r--. 1 vagrant vagrant   64 Feb 26 15:30 /home/vagrant/a
-rwxrwxr-x. 1 vagrant vagrant  241 Dec 10 15:31 /home/vagrant/bashscript.sh
-rw-rw-r--. 1 vagrant vagrant 3327 Nov 13 12:07 /home/vagrant/id_rsa
-rw-rw-r--. 1 vagrant vagrant  439 Feb 26 15:30 /home/vagrant/lastmodifyofifle.sh

Using stat command as below

[vagrant@app1 ~]$ stat --format='%a %U:%G %n' /home/vagrant/*

The result as below

664 vagrant:vagrant /home/vagrant/a
775 vagrant:vagrant /home/vagrant/bashscript.sh
664 vagrant:vagrant /home/vagrant/id_rsa
664 vagrant:vagrant /home/vagrant/lastmodifyofifle.sh

You make it 🙂

Conclusion

You have to get permission of chmod as numerical value on Linux. I hope will this your helpful. Thank you for reading the DevopsRoles page!

Configure SSH connection with key authentication

In this tutorial, I will configure the SSH connection with key authentication.

How it works

  • (Client) Generate a set of secret key and public key
  • (Connection destination server) Register public key
  • (Connection destination server) Accepts a connection from a client, encrypts the random number using the public key
  • (Connection destination server) Hashed random number
  • (Client) hashes the received random number and forwards the hash value to the server
  • (Connection destination server) Compare the hash value sent by the client and the hash value generated on the server side

Set up SSH connection with key authentication.

1: Generation of a key set

ssh-keygen -t rsa -f client01

2: Public Key Registration

# Work on the server, target users to connect
cat client01.pub >> .ssh/authorized_keys

3: Enabling Key Authentication

  # vim /etc/ssh/sshd_config
  RSAAuthentication yes
  PubkeyAuthentication yes
  AuthorizedKeyFile .ssh/authorized_keys
  # Disable password authentication if you want to strengthen it
   PasswordAuthentication no

Try to connect

ssh -i .ssh/client01 -p12345 huupv@devopsroles

Conclusion

Thought the article, How to configure SSH connection with key authentication in Linux. Thank you for reading the DevopsRoles page!

systemd service unit notes

In this tutorial, The describe service unit notes.

  • is a system and service manager for Linux.
  • init is no longer an old Linux.
  • Only the command can be used for starting and stopping.

systemd service unit file

  • It is arranged under “/etc/systemd/system” with “unitname.service
  • Others include directories like “/usr/lib/systemd” and “/lib/systemd“, but rather for systems.

Service section

Describe the operation parameters of the unit.

Type

The relationship between the execution command and the main process is represented by Type.

  • simple: ExecStart command remains as it is process
  • forking: Child process of ExecStart is process
  • : Even if ExecStart ends, the main process will remain.

Restart

Restart conditions can be specified with parameters equivalent to respawn in the old inittab.

  • always: always rerun
  • on-abort: re-execute when terminating with a signal that can not be caught
  • on-watchdog: Rerun with monitor timeout
  • on-abnormal: Re-execution when terminating with a signal other than SIGHUP, SIGINT, SIGTERM or SIGPIPE
  • on-failure: re-execution when the main process ends with a code other than the normal termination code
  • on-success: Rerun when the main process ends with a normal exit code

Install section

Specify which target (old ) should be executed when th is activated ( enable).

For example, when enabling in multi-user mode (old run level 3), a symbolic link to a unit file is established under “/etc//system/multi-user.target“.

[Unit]
Description=Description
After=Execute after starting the specified unit list
Before=Execute before the specified unit list
Requires=Execute after the specified unit list has been successfully started
Wants=Even if the specified unit list fails to start up

[Service]
Environment=environment variable list
EnvironmentFile=environment variable file
Type=simple|forking|oneshot
ExecStart=start command
ExecStop=stop command
ExecReload=reload command
Restart=On-abort|on-watchdog|on-abnormal|on-failure|on-success|no
RemainAfterExit=yes|no
PIDFile=PID file path of main process
User=ExecXX execution user
SuccessExitStatus=(other than 0) EXIT code list to be regarded as a normal completion of the main process

[Install]
Alias=service alias list
WantedBy=target list
Also=unit list installed together

used commands

Unit file installation (loading)

$ sudo systemctl daemon-reload

Enable/disable

$ systemctl enable|disable unitname

Dependency display

$ systemctl list-dependencies unitname

For example, List Dependency of chronyd package.

Confirm startup sequence

Summary of time spent on startup (kernel, initrd, user)

$ systemd-analyze time

Time is taken to activate unit (currently active unit)

$ systemd-analyze blame

SVG output startup sequence

$ systemd-analyze plot > systemd.sequence.svg 

Confirm log

$ journalctl -xe 
$ journalctl -xe -S "2019-01-22 23:00:00"  
$ journalctl -xe -S "2019-01-22 23:00:00" -U "2019-01-22 23:10:00" 
$ journalctl -xe -u unitname
$ journalctl -f -u servicename 
$ journalctl --disk-usage

$ lsof -p $(pidof systemd-journald)

Reference information

  • man .service
  • man -analyze

unit file example

Apache system (fork daemon)

myhttpd.service unit file

[Unit]
Description=HTTP Server
After=web.service

[Service]
Type=forking
ExecStart=/opt/bin/apachectl start
ExecStop=/opt/bin/apachectl graceful-stop
PIDFile=/opt/logs/httpd.pid
Restart=on-failure

[Install]
WantedBy=multi-user.target

web.service unit file

[Unit]
Description=WebSphere Application Server apserver
After=network.target network.service

[Service]
Type=forking
ExecStart=/opt/AppServer/profiles/AppSrv01/bin/startServer.sh apserver
ExecStop=/opt/AppServer/profiles/AppSrv01/bin/stopServer.sh apserver
PIDFile=/opt/AppServer/profiles/AppSrv01/logs/apserver/apserver.pid
Restart=on-failure
User=webuser
SuccessExitStatus=143 0
TimeoutStopSec=0
TimeoutStartSec=0

[Install]
WantedBy=multi-user.target

systemd service unit notes. Thank you for reading the DevopsRoles page!

Docker Images history

The size of the Docker Image was suddenly increasing, I will check it. Using docker history <Image name> you can check the change history for Image before. Now, let’s Docker Images history.

Docker Images history

Docker pull command

Requires Image to be downloaded locally. As an example, I use docker pull image centos as below

[vagrant@localhost ~]$ docker pull centos:6.10
6.10: Pulling from library/centos
1c8f9aa56c90: Pull complete
Digest: sha256:b4c3fe75b135ca1c26ef6feb8153aade8a31c4e3e763376529c1088de7e973f4
Status: Downloaded newer image for centos:6.10

[vagrant@localhost ~]$ docker images
REPOSITORY          TAG                 IMAGE ID            CREATED             SIZE
centos              6.10                30e66b619e9f        4 months ago        194MB

Try it

The output order is new, and it seems that it becomes an old layer as going down as below

[vagrant@localhost ~]$ docker history centos:6.10
IMAGE               CREATED             CREATED BY                                      SIZE                COMMENT
30e66b619e9f        4 months ago        /bin/sh -c #(nop)  CMD ["/bin/bash"]            0B
<missing>           4 months ago        /bin/sh -c #(nop)  LABEL org.label-schema.sc…   0B
<missing>           4 months ago        /bin/sh -c #(nop) ADD file:769078df784180af4…   194MB

Also, With the “–human” option, the actual date is displayed below

[vagrant@localhost ~]$ docker history centos:6.10 --human=false
IMAGE               CREATED AT                  CREATED BY                                      SIZE                COMMENT
30e66b619e9f        2018-10-10T01:22:51+07:00   /bin/sh -c #(nop)  CMD ["/bin/bash"]            0
<missing>           2018-10-10T01:22:51+07:00   /bin/sh -c #(nop)  LABEL org.label-schema.sc…   0
<missing>           2018-10-10T01:22:51+07:00   /bin/sh -c #(nop) ADD file:769078df784180af4…   193889316

Docker inspect container information

Using docker inspect command to Confirmation of container information.

[vagrant@localhost ~]$ docker inspect centos:6.10
[
    {
        "Id": "sha256:30e66b619e9f73941f418bb08a081132607433f5b8ccaefd3b7bceb08c770b20",
        "RepoTags": [
            "centos:6.10"
        ],
        "RepoDigests": [
            "centos@sha256:b4c3fe75b135ca1c26ef6feb8153aade8a31c4e3e763376529c1088de7e973f4"
        ],
        "Parent": "",
        "Comment": "",
        "Created": "2018-10-09T18:22:51.586650744Z",
        "Container": "9a31860c3402344acd1f16127fec864b93038c86e8716f08e5dc2a60851a602e",
        "ContainerConfig": {
            "Hostname": "9a31860c3402",
            "Domainname": "",
            "User": "",
            "AttachStdin": false,
            "AttachStdout": false,
            "AttachStderr": false,
            "Tty": false,
            "OpenStdin": false,
            "StdinOnce": false,
            "Env": [
                "PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin"
            ],
            "Cmd": [
                "/bin/sh",
                "-c",
                "#(nop) ",
                "CMD [\"/bin/bash\"]"
            ],
            "ArgsEscaped": true,
            "Image": "sha256:34321cccc68dac29b496363ca05c47e7f23c3e59d664fea4de03695975443b8b",
            "Volumes": null,
            "WorkingDir": "",
            "Entrypoint": null,
            "OnBuild": null,
            "Labels": {
                "org.label-schema.build-date": "20180804",
                "org.label-schema.license": "GPLv2",
                "org.label-schema.name": "CentOS Base Image",
                "org.label-schema.schema-version": "1.0",
                "org.label-schema.vendor": "CentOS"
            }
        },
        "DockerVersion": "17.06.2-ce",
        "Author": "",
        "Config": {
            "Hostname": "",
            "Domainname": "",
            "User": "",
            "AttachStdin": false,
            "AttachStdout": false,
            "AttachStderr": false,
            "Tty": false,
            "OpenStdin": false,
            "StdinOnce": false,
            "Env": [
                "PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin"
            ],
            "Cmd": [
                "/bin/bash"
            ],
            "ArgsEscaped": true,
            "Image": "sha256:34321cccc68dac29b496363ca05c47e7f23c3e59d664fea4de03695975443b8b",
            "Volumes": null,
            "WorkingDir": "",
            "Entrypoint": null,
            "OnBuild": null,
            "Labels": {
                "org.label-schema.build-date": "20180804",
                "org.label-schema.license": "GPLv2",
                "org.label-schema.name": "CentOS Base Image",
                "org.label-schema.schema-version": "1.0",
                "org.label-schema.vendor": "CentOS"
            }
        },
        "Architecture": "amd64",
        "Os": "linux",
        "Size": 193889316,
        "VirtualSize": 193889316,
        "GraphDriver": {
            "Data": {
                "MergedDir": "/var/lib/docker/overlay2/f799911e2d9e2de958ee359b6a6e125a93a69992c34851acb63ec1f22e2f9da2/merged",
                "UpperDir": "/var/lib/docker/overlay2/f799911e2d9e2de958ee359b6a6e125a93a69992c34851acb63ec1f22e2f9da2/diff",
                "WorkDir": "/var/lib/docker/overlay2/f799911e2d9e2de958ee359b6a6e125a93a69992c34851acb63ec1f22e2f9da2/work"
            },
            "Name": "overlay2"
        },
        "RootFS": {
            "Type": "layers",
            "Layers": [
                "sha256:18c81886066a186e754291bab5ae87b273b274c66c2c9fea8e869a7cb67dac1b"
            ]
        },
        "Metadata": {
            "LastTagTime": "0001-01-01T00:00:00Z"
        }
    }
]

Extract only environment variables as below

[vagrant@localhost ~]$ docker inspect --format='{{range .Config.Env}}{{println .}}{{end}}' centos:6.10
PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin

Conclusion

Through the article, You can inspect “Docker images history” as above. I hope will this your helpful. Thank you for reading the DevopsRoles page!

Nginx reverse proxy for Jenkins in docker

Introduction

In this tutorial, I use Nginx reverse proxy for Jenkins in docker as the whole picture below

Nginx reverse proxy for Jenkins in docker

Procedure as below

  • Host OS: Install Nginx and Docker. Using account root for setup server.
  • Docker containers: Jenkins and app_devops

Installing and Configuring on CentOS/RedHat 7/6

Install Epel and Remi repository on CentOS/RedHat 6/7

### Install Epel For CentOS/RHEL 7 ###
# rpm -Uvh http://dl.fedoraproject.org/pub/epel/7/x86_64/Packages/e/epel-release-7-11.noarch.rpm

### Install Epel For CentOS/RHEL 6 ###
# rpm -Uvh http://dl.fedoraproject.org/pub/epel/6/x86_64/epel-release-6-8.noarch.rpm

### Install REMI Repository For CentOS/RHEL 7 ###
rpm -Uvh http://rpms.famillecollet.com/enterprise/remi-release-7.rpm

### Install REMI Repository For CentOS/RHEL 6 ###
rpm -Uvh http://rpms.famillecollet.com/enterprise/remi-release-6.rpm

Docker install

Nginx install

# yum install nginx

start Nginx service

# service nginx start

Set up Jenkins with docker

Nginx configure

Creating Nginx configuration file directory for myapp

# mkdir /etc/nginx/conf.d/myapp/

Backup the default configuration file

# mv /etc/nginx/conf.d/default.conf  /etc/nginx/conf.d/default.conf_bk

Create the configuration file for myapp

# vi /etc/nginx/conf.d/server.conf

The content is below

server {
    listen       80;
    include /etc/nginx/default.d/*.conf;
    root         /usr/share/nginx/html;
    #common
    proxy_set_header    Host $host:$server_port;
    proxy_set_header    X-Real-IP    $remote_addr;
    proxy_set_header    X-Forwarded-Host       $host:$server_port;
    proxy_set_header    X-Forwarded-Server    $host:$server_port;
    proxy_set_header    X-Forwarded-For    $proxy_add_x_forwarded_for;
    proxy_set_header    X-Forwarded-Proto $scheme;

    include /etc/nginx/conf.d/myapp/*.conf;
}

Nginx reverse proxy for devopsroles.com and jenkins Configuring

Creating file devops.conf in folder myall

# vi /etc/nginx/conf.d/myapp/devops.conf

The content is below

#for myapp
location /devopsroles/ {
    proxy_pass    http://localhost:68081/;
    proxy_redirect  http://localhost:68081/ /devopsroles/;

}

# For jenkins
location /dev_jenkins/ {
    proxy_pass    http://localhost:68080 ;
    proxy_redirect  http://localhost:68080/ /dev_jenkins/;
}

Conclusion

Through the article, You can set up “ Nginx reverse proxy for Jenkins in docker as above. I hope will this your helpful. Thank you for reading the DevopsRoles page!

Directory size displayed by du command does not match

When the directory size displayed by the du command does not match between the parent directory and child directory in Linux. How to solve the problem? The parent directory is and the child hidden directory is “.delete”

du command does not match directory size displayed

Folder devopsroles with 12M size as below

[huupv@server01 ~]$  du -sh devopsroles
12M     devopsroles

Contain files and folders in devopsroles as below

[huupv@server01 devopsroles]$ ls -la
total 16
drwxr-xr-x  3 huupv huupv 4096 Feb 13 16:29 .
drwxr-xr-x 16 huupv huupv 4096 Feb 13 16:29 ..
drwxr-xr-x  2 huupv huupv 4096 Feb 13 16:07 .delete
-rw-r--r--  1 huupv huupv   17 Feb 13 16:29 note.txt
-rw-r--r--  1 huupv huupv    0 Feb 13 16:29 tmp.txt

In folder devopsroles different size with du -sh command.

[huupv@server01 ~]$ cd devopsroles/
[huupv@server01 devopsroles]$ pwd
/home/huupv/devopsroles
[huupv@server01 devopsroles]$ du -sh ./* | sort -hr
4.0K    ./note.txt
0       ./tmp.txt

12M=4.0K + 0? Why does not it match?

Cause: du command does not show hidden directory size.

If you do the following, the file size including the hidden directory is displayed as the command below.

[huupv@server01 devopsroles]$ du -sh .[^.]*/ ./* | sort -hr
12M     .delete/
4.0K    ./note.txt
0       ./tmp.txt

Conclusion

In this tutorial, you can solve the problem “directory size displayed by du does not match between the parent directory and child directory” in Linux. Thank you for reading the DevopsRoles page!

Docker tutorial series – part 2

In this article, I will write about “data mount (volume), Docker Network, Docker Compose”. Now, let’s go Docker tutorial series – part 2.

Data management in Docker

Dynamic data to be handled in the started container can be placed in the top layer (container layer) that can be read and written.

  • When the container is deleted, data in the container disappears.
  • Can not share data among containers.
  • Since writing to the container layer uses a union file system different from the normal file system, the writing speed is slow.

Disadvantage

Docker manages data on the host machine and mounts it on the container is used.

There are three main methods, which I will explain below.

volume

A method of mounting the specified directory (/var/lib/docker/volumes) which is automatically generated on the host machine to the container

On the host machine

$ docker volume create [volume name]

By doing so, When you create a volume (/var/lib/docker/volumes directory) and start up the container.

For example
$ docker run -itd -name mount-test --mount source=volume1,target=/app nginx

You can mount the specified volume by attaching the –mount option (it can also be the -v option) as shown in.

The mounted volumes directory should not be directly manipulated from the directory on the host from which it is mounted.

Even different containers that are set up on the same host can share files by mounting the same volume respectively.

Furthermore, if you want to share volume with multiple containers, you can also set edit permission for each container.

$ docker run -itd -name mount-c4 --mount source=copy-vol,destination=/etc/nginx,readonly nginx

volume management command

Check volume list

$ docker volume ls

Check volume details

$ docker volume inspect [volume name]

Delete volume

$ docker volume rm [volume name]

Note that deleting the container will keep the volume, so you need to delete it with the $docker volume rm [volume name].

bind mount

Bind mount is a mount method different from the volume, in that you can mount arbitrary directories on the host machine and directly manipulate directories on the host side.

It is not necessary to set it in advance like volume, but mount it by specifying it as an option at container startup with the following command.

For example:
$ docker run -itd -name bind-mount-test --mount type=bind,source="$ (pwd)"/mount,target=/app nginx

If the source (mount source) directory does not exist, an error will occur, so let’s make it in advance. (It is automatically created when using the -v option)

if you mount an empty directory on the host. on the container, data on the container will disappear and the container may not work properly, so be careful.

tmpfs (tempfs)

A method of mounting the memory area of the host machine on the container

Whether the host machine is terminated or when the container is closed, the held data is released.

For example:
$ docker run --itd --name tmpfs-test --mount type=tmpfs,destination=/app nginx

You can mount by specifying as the type of the -mount option at the time of container startup.

Also, in order to eliminate the possibility of unlimited use of memory on the host,

$ docker run --itd --name tmpfs-test --mount type=tmpfs,destination=/app,tmpfs-size=100000000,tmpfs-mode=800 nginx

You can also limit the memory size that can be used as an option.

Docker network

we will explain here the method of communicating between multiple containers launched.

For example, when operating a web page, if you start up a WordPress container and a MySQL container, the WordPress container needs to communicate with the MySQL container.

As a method of inter-container communication here, it is the Docker network that connects and communicates with multiple containers.

The Docker network has three networks that exist by default and networks that you define yourself.

Bridge network

In the existing network by default, the created container is connected by default to the bridge network.

In the Bridge network, you can communicate with a container that exists in the same network by specifying an IP address.
However, in the Bridge network, since DNS is not defined, the container name can no communicate with other containers.

In other words, it is possible to communicate by specifying an IP address among containers launched without specifying Network, but it is impossible to communicate by specifying a container name.

Although it is a network that is not exposed to the outside in the default state, it can be accessed from the outside by releasing the port specified by the -p option.

Host network

The host network is the network that exists by default with the host driver.

The connected container will have the same network settings as the docker host.

Therefore, it is possible to connect to the container by connecting to the Docker host’s IP number 80 only by starting the container without setting the -p option at the container startup and opening the port to the outside like the bridge network I will.

None Network

It is the default existing network, and the connected container has no network interface. When connecting to a network, it is necessary to be disconnected from all other networks.

Docker create

By creating your own network, you can communicate between containers by container name.

$ docker network create [network name]

Create a new network with (Default driver is a bridge)

$ docker network connect [Network name to connect to] [Container name]

Docker Daemon’s built-in DNS works on the user-defined unique network resolve names by container name and associates with IP, so you can connect to other containers by container name.

Network commands

Check the network list

$ docker network ls

Check network details

$ docker network inspect [network name]

Create a new network

$ docker network create [network name]

The default driver is bridge

Connect a container to a network

$ docker network connect[ Network name to connect to] [Container name]

Disconnect container from a network

$ docker network disconnect Network name container name

Docker Compose

Docker Compose is a tool for predefining and running multiple container Docker applications. So, Docker Compose is able to automate them.

When building the execution environment of a Web service with Docker, by writing the definitions of the Web server, DB server, Cache server, etc. in one docker-compose.yml file, based on that, the container required for execution You can start and set all at once.

The procedure is as follows.

  • Prepare a Dockerfile or prepare an image to use for Docker Hub etc.
  • Define docker-compose.yml
  • Execute $ docker-compose up in the directory containing the yml file

docker-compose command list

Display a list of containers started with docker-compose

$ docker-compose ps

Container activation from the setting described in docker-compose.yml

$ docker-compose up

It restarts even if the container is already running

Delete containers and networks created with docker-compose

$ docker-compose down
# $ docker-compose down -v

The volume is also deleted together with the -v option

Execute command within specified service container

$ docker-compose run [container name] [command]

A series of container stops

$ docker-compose stop

A series of container activation

$ docker-compose start

Docker tutorial series – part 1

Docker tutorial series part 1

In this article, I will Write about understanding the mechanism of Docker. The whole picture of various concepts around Docker. Now, let’s go Docker tutorial series part 1.

docker-compose
docker-machine
docker swarm, etc. from the basics of images and containers.

In the Docker tutorial series part 1

I will write about “the container, image, image sharing with DockerHub“.

What is Docker

It is “container type virtualization technology” provided by Docker.

What is Virtualization?

  • Virtual computer in PC or Server” is virtualization.
  • Host operating system installed on a machine such as PC or server.
  • Hosted virtualization uses a virtualization software/hypervisor on a Host OS to launch a Virual Machine call is Guest OS

Container type virtualization?

  • Docker provides container type virtualization.
  • Containers are build from Docker Engine running on Host OS without booting guest OS.

Docker Engine

Docker Engine will operate as a resident program and you can use Docker.

Tag

The Docker image has the concept of tag. Tag is the “version of image”. If no tag name is specified, the “latest” tag is automatically used.

For example, the image name and tag name as below

nginx: latest
nginx: 1.14-wordpress

image structure

  • it has a layer structure
  • Once created image is not editable (read only)

The layer of the image is Read-only, it can not be edited, only the container layer created when the container is activated from an image can be edited.

List image on the local machine as command below

$ docker images

How to prepare image

  • Obtain an image made by others (mainly from Docker Hub)
  • Make it yourself

I will go through step by step

1. Image from Docker Hub

Retrieve image from #dockerhub (server hosted by docker)

$ docker pull <image name>

2. Image creation from Dockerfile

Create a text file named Dockerfile, describe the settings related to image build (image creation) in it.

Dockerfile example

# CentOS 7 Dockerfile
 # Docker build:
 # sudo docker build -t devopsroles/centos:latest .
 # Docker create:
 # sudo docker create -it --name centos -h centos devopsroles/centos
 # Docker start:
 # sudo docker start centos
 # Connect with bash
 # sudo docker exec -it centos bash
 FROM centos:latest
 MAINTAINER PHAN VAN HUU <pvhuu90@gmail.com> My blogs: devopsroles.com
 #Update centos
 RUN yum update -y && yum upgrade -y
 RUN yum -y install git curl net-tools wget vim
 # Install EPEL Repository
 RUN yum install -y epel-release
 # Clean CentOS 7
 RUN yum clean all
 # Set the environment variables
 ENV HOME /root
 # Working directory
 WORKDIR /root
 # Default command
 CMD ["bash"]

Docker build the image from our Dockerfile

$ sudo docker create -it --name centos -h centos devopsroles/centos

Docker Container

After preparing the image, the container can be started from the image.

Launch container from image

Create containers from images as command below

$ docker create --name centos

As a command to acquire and start a container by acquiring the specified image that we have seen from DockerHub. Launch Container as command below

$ docker start <Container name>

The docker run command is the command to execute at the same time.

$ docker run <image name>
  • Retrieve images from DockerHub : docker pull
  • Create container from acquired image: docker create
  • Start up the created container: docker start

Docker container commands

Show currently running Container

$ docker ps

Display container list currently existing

$ docker ps -a

Display detailed information of the container

$ docker inspect <container name>

Create Container

$ docker create --name <arbitrary name of container> -it <image name> /bin/bash

Launch Container with the command below

$ docker start <container name>

You can pause containers

$ docker pause <container name>

you can cancel the pause of the container with the command below

$ docker unpause <container name>

Restarting the container. If you do not use containers you do not use, your hard disk will be pressured.

$ docker stop <container name>

Delete Container

$ docker rm <container name>

Forced removal container

$ docker rm -f <container name>

Connect to the shell of the active container

There are two connection methods, using docker attach and docker exec

$ docker attach <Starting Container Name>
$ docker exec -it <Starting Container Name> /bin/bash

Create an image from a container

A command to save the state of the container as an image with the specified “<image name>: <tag name>

$ docker commit <container name> <image name>:<tag name>

You can check the change history of the image

$ docker history <image name>

3. Docker Hub (Docker Registry)

Sharing images with Docker Hub

It is almost the same as Github. You need to have a Dockerhub account.

As a procedure

  • Create repository on Docker hub
  • Create image locally
  • Log in to the docker hub with the following command on the local command line
$ docker login

4. Tag the image you want to push with the following command

$ docker tag <image name you want to push> <docker hub ID>/<image name>:<tag name>

5. Push the local image to the remote repository with the following command

$ docker push <docker hub ID>/<image name>:<tag name>

Docker tutorial series – part 2

Devops Tutorial

Exit mobile version