---
# System prepended metadata

title: Docker - Install and Usage
tags: [Docker, Usage, Install]

---

# Docker - Install and Usage

###### tags: `Docker` `Install` `Usage`
 
# Frequent use commands

* List all containers: 
```
docker ps -a
```

``docker ps --filter "status=exited"``

* List all images:
```
docker images
```

* Start a certain container:
```
docker start [container_id]
docker start 4bfc4786d978 
```

* Stop a certain container: 
```
docker stop [container_id]
docker stop 42ae7abb010b
```

* Remove a certain container: 
```
docker rm [container_id]
docker rm 42ae7abb010b
```

* See the log of a certain container: 
```docker logs [container_id]
docker logs 42ae7abb010b
```





---
 
# Ubuntu installation

## [Install Docker Engine on Ubuntu](https://docs.docker.com/engine/install/ubuntu/)

### Install using the repository

#### SET UP THE REPOSITORY

1. Update the apt package index and install packages to allow apt to use a repository over HTTPS:
```
sudo apt-get update
sudo apt-get install apt-transport-https ca-certificates curl gnupg-agent software-properties-common
```

2. Add Docker’s official GPG key:
```
curl -fsSL https://download.docker.com/linux/ubuntu/gpg | sudo apt-key add -
```

Verify that you now have the key with the fingerprint 
``9DC8 5822 9FC7 DD38 854A  E2D8 8D81 803C 0EBF CD88``, 
by searching for the last 8 characters of the fingerprint.

```
sudo apt-key fingerprint 0EBFCD88
```

```
pub   rsa4096 2017-02-22 [SCEA]
      9DC8 5822 9FC7 DD38 854A  E2D8 8D81 803C 0EBF CD88
uid           [ unknown] Docker Release (CE deb) <docker@docker.com>
sub   rsa4096 2017-02-22 [S]
```

3. Use the following command to set up the stable repository. 

x86_64 / amd64:
```
sudo add-apt-repository "deb [arch=amd64] https://download.docker.com/linux/ubuntu $(lsb_release -cs) stable"
```

#### INSTALL DOCKER ENGINE

1. Update the apt package index, and 
install the latest version of Docker Engine and containerd

```
sudo apt-get update
sudo apt-get install docker-ce docker-ce-cli containerd.io
```

```
以下套件為自動安裝，並且已經無用：
  linux-hwe-5.4-headers-5.4.0-42 linux-hwe-5.4-headers-5.4.0-45
  linux-hwe-5.4-headers-5.4.0-47 linux-hwe-5.4-headers-5.4.0-48
  linux-hwe-5.4-headers-5.4.0-51 linux-hwe-5.4-headers-5.4.0-52
  linux-hwe-5.4-headers-5.4.0-53 linux-hwe-5.4-headers-5.4.0-56
  linux-hwe-5.4-headers-5.4.0-58
使用 'sudo apt autoremove' 將之移除。
下列的額外套件將被安裝：
  docker-ce-rootless-extras pigz
建議套件：
  aufs-tools cgroupfs-mount | cgroup-lite
推薦套件：
  slirp4netns
下列【新】套件將會被安裝：
  containerd.io docker-ce docker-ce-cli docker-ce-rootless-extras pigz
```

2. Verify that Docker Engine is installed correctly by running the ``hello-world`` image.

```
sudo docker run hello-world
```


#### 但我在 Ubuntu 遇到下面 permission 問題:

```
docker: Got permission denied while trying to connect to the Docker daemon socket 
at unix:///var/run/docker.sock: Post http://%2Fvar%2Frun%2Fdocker.sock/v1.24/containers/create: dial unix /var/run/docker.sock: connect: permission denied.
See 'docker run --help'.
```

--- 

## [How to fix docker: Got permission denied while trying to connect to the Docker daemon socket](https://www.digitalocean.com/community/questions/how-to-fix-docker-got-permission-denied-while-trying-to-connect-to-the-docker-daemon-socket)

Hello,

According to the official Docker docs here:

https://docs.docker.com/install/linux/linux-postinstall/#manage-docker-as-a-non-root-user

You need to do the following:

To create the docker group and add your user:

* Create the docker group.
```
sudo groupadd docker
```

* Add your user to the docker group.
```
sudo usermod -aG docker ${USER}

sudo usermod -a -G docker ${USER}
```

我的 case : ``sudo usermod -a -G docker elite_lin``

* You would need to loog out and log back in so that your group membership is re-evaluated or type the following command:
```
su -s ${USER}
```

* Verify that you can run docker commands without sudo.
```
docker run hello-world
```

* This command downloads a test image and runs it in a container. When the container runs, it prints an informational message and exits.
* If you initially ran Docker CLI commands using sudo before adding your user to the docker group, you may see the following error, which indicates that your ``~/.docker/`` directory was created with incorrect permissions due to the sudo commands.

> WARNING: Error loading config file: /home/user/.docker/config.json -
stat /home/user/.docker/config.json: permission denied

* To fix this problem, either remove the ``~/.docker/`` directory 
(it is recreated automatically, but any custom settings are lost), 
or change its ownership and permissions using the following commands:
```
sudo chown "$USER":"$USER" /home/"$USER"/.docker -R
sudo chmod g+rwx "$HOME/.docker" -R
```

---

## [Solving Docker permission denied while trying to connect to the Docker daemon socket](https://medium.com/@dhananjay4058/solving-docker-permission-denied-while-trying-to-connect-to-the-docker-daemon-socket-2e53cccffbaa)

## Problem:
You are trying to run a docker container or do the docker tutorial, 
but you only get an error message like this:

```
docker: Got permission denied while trying to connect to the Docker daemon socket 
at unix:///var/run/docker.sock: 
Post http://%2Fvar%2Frun%2Fdocker.sock/v1.26/containers/create: 
dial unix /var/run/docker.sock: connect: permission denied.
See 'docker run --help'.
```

## Solution:
The error message tells you that 
your current user can’t access the docker engine, 
because you’re lacking permissions to access the unix socket 
to communicate with the engine.

As a temporary solution, you can use ``sudo`` to run the failed command as ``root`` 
(e.g. ``sudo docker ps``).
However it is recommended to fix the issue 
by adding the current user to the docker group:

Run this command in your favourite shell and 
then completely log out of your account and log back in 
(or exit your SSH session and reconnect, if in doubt, 
reboot the computer you are trying to run docker on!):
```
sudo usermod -a -G docker $USER
```

輸入這項指令後，要登出，然後重新登入

After doing that, you should be able to run the command without any issues. 
Run ``docker run hello-world`` as a normal user in order to check if it works. 
Reboot if the issue still persists.

See What does [``sudo usermod -a -G group $USER``](https://medium.com/@dhananjay4058/what-does-sudo-usermod-a-g-group-user-do-on-linux-b1ab7ffbba9c) do on Linux? for details 
on what this command changes on your system and what the parameters mean.

Logging out and logging back in is required 
because the group change will not have an effect unless your session is closed.

## Background information:

On Linux, when you run any ``docker`` command, 
the ``docker`` binary will try to connect to ``/var/run/docker.sock``. 
As indicated by its ``.sock`` extension, 
this file is a [Unix Domain Socket](https://en.wikipedia.org/wiki/Unix_domain_socket) – 
basically, __a way so multiple processes can communicate on the local computer__ 
(also called an IPC mechanism – IPC = “Inter-Process Communication”).

In the case of Docker, the main reason for using the socket is that 
any user belonging to the ``docker`` group can connect to the socket 
while the Docker daemon itself can run as ``root``. 
Essentially, it’s a convenience feature and 
allows multiple docker client commands 
to communicate to the same daemon process internally.

---

## [How To List / Start / Stop Docker Containers](https://phoenixnap.com/kb/how-to-list-start-stop-docker-containers)

### List Docker Containers

* To list all running Docker containers, enter the following into a terminal window:
```
docker ps
```

* To list all containers, both running and stopped, add ``–a`` :
```
docker ps –a
```

or
```
docker container ls -a
```

```
CONTAINER ID   IMAGE                 COMMAND        CREATED          STATUS                      PORTS     NAMES
68eea4debb05   portainer/portainer   "/portainer"   8 minutes ago    Exited (1) 3 minutes ago              pensive_black
c752e1c6466a   portainer/portainer   "/portainer"   8 minutes ago    Created                               cranky_mcclintock
43650331ba31   portainer/portainer   "/portainer"   9 minutes ago    Exited (1) 4 minutes ago              distracted_torvalds
522a0bfa4eb0   ubuntu                "bash"         36 minutes ago   Exited (0) 35 minutes ago             sad_hamilton
4bfc4786d978   hello-world           "/hello"       36 minutes ago   Exited (0) 36 minutes ago             priceless_banzai
bd0f0657d932   hello-world           "/hello"       2 hours ago      Exited (0) 2 hours ago                sharp_mcclintock
```


* To list containers by their ID use ``–aq`` (quiet):
```
docker ps –aq
```

### Start Docker Container

* The main command to launch or start a single or multiple stopped Docker containers is docker start:

```
docker start [options] container_id 
```

```
docker start 4bfc4786d978 
```

You can specify the container by either using its name or ID (long or short).

* To create a new container from an image and start it, use ``docker run``:

```
docker run [options] image [command] [argument] 
```

* __If you do not define a name for your newly created container, 
the deamon will generate a random string name. 
To define container name, use the ``––name`` option__:

```
docker run ––name=Ubuntu_Test ubuntu:14.04
```

The above mentioned command will create the ``Ubuntu_test`` container 
based on the ``ubuntu:14.04`` image and start it.


* A container may be running, but you may not be able to interact with it. 
To __start the container in interactive mode__, 
use the ``–i`` and ``–t`` options:

```
docker run –it ––name=Ubuntu_Test ubuntu:14.04
```

The above mentioned command will create the ``Ubuntu_test`` container 
based on the ``ubuntu:14.04`` image and start it.

```
docker run –it ––name=Test2 ubuntu
```
In the above mentioned example, the system creates the ``Test_2`` container 
from the ``ubuntu`` image, and connects to it 
enabling you to run commands directly on the container.


* Instead of using ``-i`` or ``-t`` options, 
use the ``attach`` command to connect to a running container:

```
docker attach container_id
```

### Stop Docker Container

Use the ``docker stop`` command to stop a container:
```
docker stop [option] container_id
```

Replace ``container_id`` with the container’s name or ID.

* By default, you get a 10 second grace period. 
The ``stop`` command instructs the container to stop services after that period. 
Use the ``--time`` option to define a different grace period expressed in seconds:

```
docker stop --time=20 container_id
```

To immediately ``kill`` a docker container 
without waiting for the grace period to end use:

```
docker kill [option] container_id
```

* To stop all running containers, enter the following:

```
docker stop $(docker ps –a –q)
```

The same command could be used with ``kill``. 
This would stop all containers without giving them a chance to exit.


---

## [docker run](https://docs.docker.com/engine/reference/commandline/run/)

* ``docker run``:
Usage
```
docker run [OPTIONS] IMAGE [COMMAND] [ARG...]
```
Description
Run a command in a new container

* ``docker rm``:
Usage
```
docker rm [OPTIONS] CONTAINER [CONTAINER...]
```
Description
Remove one or more containers

* ``docker stop``
Usage
```
docker stop [OPTIONS] CONTAINER [CONTAINER...]
```
Description
Stop one or more running containers

---

## Copy file from host to container

* [How to copy files from host to Docker container?](https://stackoverflow.com/questions/22907231/how-to-copy-files-from-host-to-docker-container?rq=1)
* [Copying files from host to Docker container](https://www.edureka.co/community/10534/copying-files-from-host-to-docker-container)

format:
```
docker cp /hostfile  (container_id):/(to_the_place_you_want_the_file_to_be)
```

##

my case:
```
docker cp /home/elite_lin/AWS/gfi_sso_db1-2021-02-08 yaml_defs_database_1:/home/
```


---

很多 image 需要 login 才能下載!

需要在 https://hub.docker.com/ Sign up 
然後 Create Access Token

Security 
![](https://i.imgur.com/ijwW7gZ.png)

New Access Token
![](https://i.imgur.com/5f1owhS.png)

Input Description
![](https://i.imgur.com/35UuXjc.png)

Then Keep your token string
![](https://i.imgur.com/QnyLGEs.png)

然後 login
```
docker login -u ``your_docker_id``
```

要求輸入密碼時, 再貼上/ input token string!!

Google: ``docker incorrect username or password``

[Credentials do not work for "docker login"](https://stackoverflow.com/questions/40872558/credentials-do-not-work-for-docker-login)

https://registry-1.docker.io/v2/


