Retired: This document is a duplicate or contains incorrect/outdated information.

Get Started with Docker Formatted Container Images on Red Hat Systems

Updated -

Docker has quickly become one of the premier projects for containerizing applications. This article provides a hands-on approach to start using Docker in Red Hat Enterprise Linux 7 and RHEL Atomic by setting up a Docker registry, getting and using Docker images, and working with Docker containers.

Table of Contents

Overview

The Docker project provides the means of packaging applications in lightweight containers. Running applications within Docker containers offers the following advantages:

  • Smaller than VMs: Because Docker images contain only the content needed to run an application, saving and sharing is much more efficient with Docker containers than it is with virtual machines (which include entire operating systems)
  • Improved performance: Likewise, since you are not running an entirely separate operating system, a container will typically run faster than an application that carries with it the overhead of a whole new virtual machine.
  • Secure: Because a Docker container typically has its own network interfaces, file system, and memory, the application running in that container can be isolated and secured from other activities on a host computer.
  • Flexible: With an application's run time requirements included with the application in the container, a Docker container is capable of being run in multiple environments.

Currently, you can run Docker containers on Red Hat Enterprise Linux 7 (RHEL 7) and Red Hat Enterprise Linux Atomic (based on RHEL 7) systems. If you are unfamiliar with RHEL Atomic, you can learn more about it from Getting Started with Red Hat Enterprise Linux Atomic Host or the upstream Project Atomic site. Project Atomic produces smaller derivatives of RPM-based Linux distributions (RHEL, Fedora, and CentOS) that is made specifically to run Docker containers in OpenStack, VirtualBox, Linux KVM and several different cloud environments.

This article will help you get started with the initial release of Docker in RHEL 7 and RHEL Atomic. Besides offering you some hands-on ways of trying out Docker, it also describes how to:

  • Access RHEL-based Docker images from the Red Hat Customer Portal
  • Incorporate RHEL-entitled software into your containers

Later releases of this document will help you:

  • Leverage RHEL security features to ensure safe deployment of your containers
  • Find tools to standardize how you build Docker images
  • Offer tips for building containers in ways that are compliant with security protocols

If you are interested in more details on how Docker works, refer to the following:

  • Release Notes: Refer to the Linux Containers with Docker Format section of the RHEL 7 Release Notes for an overview of Docker features in RHEL 7.
  • Docker Project Site: From the Docker site, you can learn about Docker from the What is Docker? page and the Getting Started page. There is also a Docker Documentation page you can refer to.
  • Docker README: After you install the docker package, refer to the README.md file in the /usr/share/doc/docker-1* directory.
  • Docker man pages: Again, with docker installed, type man docker to learn about the docker command. Then refer to separate man pages for each docker option (for example, type man docker-image to read about the docker image option).

NOTE: Currently, to run the docker command in RHEL 7 and RHEL Atomic you must have root priviledge. In the procedure, this is indicated by the command prompt appearing as a hash sign (#). Configuring sudo will work, if you prefer not to log in directly to the root user account.

Getting Docker in RHEL 7

To get an environment where you can develop Docker containers, you can install a Red Hat Enterprise Linux 7 system to act as a development system as well as a container host. The docker package itself is stored in a RHEL Extras repository (see the Red Hat Enterprise Linux Extras Life Cycle article for a description of support policies and life cycle information for the Red Hat Enterprise Linux Extras channel).

Using the RHEL 7 subscription model, if you want to create Docker images or containers, you must properly register and entitle the host computer on which you build them. When you use yum install within a container to add packages, the container automatically has access to entitlements available from the RHEL 7 host, so it can get RPM packages from any repository enabled on that host.

  1. Install RHEL Server edition: If you are ready to begin, you can start by installing a Red Hat Enterprise Linux system (Server edition) as described in the following:
    Red Hat Enterprise Linux 7 Installation Guide

  2. Register RHEL: Once RHEL 7 is installed, register the system using Subscription Management tools and install the docker package. Also enable the software repositories needed. (Replace pool_id with the pool ID of your RHEL 7 subscription.) For example:

    NOTE: For this guide, we show the docker and docker-registry services running on the same host system. It is possible, in fact likely when the Docker registry is being used by multiple clients, to have docker-registry installed and running on a separate system. If that is the case, the docker-registry package is not required on a system running docker.

    # subscription-manager register --username=rhnuser --password=rhnpasswd
    # subscription-manager list --available  Find pool ID for RHEL subscription
    # subscription-manager attach --pool=pool_id
    # subscription-manager repos --enable=rhel-7-server-extras-rpms
    # subscription-manager repos --enable=rhel-7-server-optional-rpms
    

    NOTE: For information on the channel names required to get docker packages for Red Hat Satellite 5, refer to Satellite 5 repo to install Docker on Red Hat Enterprise Linux 7.

  3. Install docker and docker-registry: Install the docker package and, optionally, the docker-registry. (If not already installed, install device-mapper-libs and device-mapper-event-libs as well.)

    # yum install docker docker-registry
    # yum install device-mapper-libs device-mapper-event-libs
    
  4. Start docker:

    # systemctl start docker.service
    
  5. Enable docker:

    # systemctl enable docker.service
    
  6. Check docker status:

    # systemctl status docker.service
        docker.service - Docker Application Container Engine
           Loaded: loaded (/usr/lib/systemd/system/docker.service; enabled)
           Active: active (running) since Thu 2014-10-23 11:32:11 EDT; 14s ago
             Docs: http://docs.docker.io
         Main PID: 2068 (docker)
           CGroup: /system.slice/docker.service
                   └─2068 /usr/bin/docker -d --selinux-enabled -H fd://
        ...
    

With the docker service running, you can obtain some Docker images and use the docker command to begin working with Docker images in RHEL 7.

Getting Docker in RHEL Atomic

RHEL Atomic is a light-weight Linux operating system distribution that was designed specifically for running containers. It contains the docker service, as well as some services that can be used to orchestrate and manage Docker containers, including Kubernetes and Etcd services.

Because RHEL Atomic is more like an appliance than a full-featured Linux system, it is not made for you to install RPM packages or other software on (other than the containers that you add into the system).

RHEL Atomic has a mechanism for updating existing packages, but not for allowing users to add new packages. Therefore, you should consider using a standard RHEL 7 server system to develop your applications (so you can add a full compliment of development and debugging tools), then use RHEL Atomic to deploy your containers into a variety of virtualization and cloud environment.

That said, you can install a RHEL Atomic system and use it to run, build, stop, start, and otherwise work with containers using the examples shown in this document. To do that, use the following procedure to get and install RHEL Atomic.

  1. Get RHEL Atomic: RHEL Atomic is available from the Red Hat Customer Portal. You have the option of running RHEL Atomic as a live image (in .qcow2 format) or installing RHEL Atomic from an installation medium (in .iso format). You can get RHEL Atomic in those (and other formats) from here:

    RHEL Atomic Host Downloads

    Then follow the Getting Started with Red Hat Enterprise Linux Atomic Host instructions for setting up Atomic to run in one of several different virtual environments.

  2. Register RHEL Atomic: Once RHEL Atomic is installed, register the system using Subscription Management tools. (This will allow you to run atomic host upgrade to upgrade Atomic software, but it won't let you install additional packages using the yum command.) For example:

    # subscription-manager register --username=rhnuser --password=rhnpasswd --auto-attach
    

    IMPORTANT: Running containers with the docker command, as described in this article, does not specifically require you to register the RHEL Atomic system and attach a subscription. However, if you want to run yum install commands within a container, the container must get valid subscription information from the RHEL Atomic host or it will fail. If you need to enable repositories other than those enabled by default with the RHEL version the host is using, you should edit the /etc/yum.repos.d/redhat.repo file. You can do that manually within the container and set enabled=1 for the repository you want to use. You can also use yum-config-manager, a command-line tool for managing Yum repo files. You can use the following command to enable repos:

    # yum-config-manager --enable REPOSITORY
    

    You can also use yum-config-manager to display Yum global options, add repositories and others. yum-config-manager is documented in detail in the Red Hat Enterprise Linux 7 System Administrator's Guide in the Configuring Yum and Yum Repositories section. Since redhat.repo is a big file and editing it manually can be error prone, it is recommended to use yum-config-manager.

  3. Start using Docker: RHEL Atomic comes with the docker package already installed and enabled. So, once you have logged in and subscribed your Atomic system, here is the status of docker and related software:

    • You can immediately begin running the docker command to work with Docker images and containers.
    • The docker-registry package is not installed. If you want to be able to pull and push images between your Atomic system and a private registry, you can install the docker-registry package on a RHEL 7 system (as described next) and access that registry to store your own container images.
    • The kubernetes package, used to orchestrate Docker containers, is installed on RHEL Atomic, but it is not enabled by default. You need to enable and start several Kubernetes-related services to be able to orchestrate containers in RHEL Atomic with Kubernetes.

Working with Docker registries

A Docker registry provides a place to store and share docker containers that are saved as images that can be shared with other people. With the docker package available with RHEL and RHEL Atomic, you can pull images from the Red Hat Customer Portal and push or pull images to and from your own private registry. You see what images are available to pull from the Red Hat Customer Portal (using docker pull) by searching the Red Hat Container Images Search Page.

This section describes how to start up a local registry, load Docker images to your local registry, and use those images to start up docker containers.

Creating a private Docker registry

One way to create a private Docker registry is to use the docker-registry service. If you installed the docker-registry package in RHEL 7 (it's not available in Atomic) as described earlier in this document, you can enable and start the service as follows:

  1. Enable and start the docker-registry service: Type the following to enable, start and check the status of the docker-registry service:

    # systemctl enable docker-registry
    # systemctl start docker-registry
    # systemctl status docker-registry
    docker-registry.service - Registry server for Docker
       Loaded: loaded (/usr/lib/systemd/system/docker-registry.service; enabled)
       Active: active (running) since Thu 2014-10-23 13:40:26 EDT; 4s ago
    Main PID: 21031 (gunicorn)
       CGroup: /system.slice/docker-registry.service
               ├─21031 /usr/bin/python /usr/bin/gunicorn --access-logfile - --debug ...
       ...
    
  2. Registry firewall issues: The docker-registry service listens on TCP port 5000, so access to that port must be open to allow clients outside of the local system to be able to use the registry. This applies regardless of whether you are running docker-registry and docker or the same system or on different systems. You can open TCP port 5000 follows:

    # firewall-cmd --zone=public --add-port=5000/tcp
    # firewall-cmd --zone=public --add-port=5000/tcp --permanent
    # firewall-cmd --zone=public --list-ports
    5000/tcp
    

    or if have enabled a firewall using iptables firewall rules directly, you could find a way to have the following command run each time you boot your system:

    iptables -A INPUT -m state --state NEW -m tcp -p tcp --dport 5000 -j ACCEPT
    

Getting images from outside Docker registries

To get Docker images from a remote registry (such as Red Hat's own Docker registry) and add them to your local system, use the docker pull command. Always explicitly indicate a target repository when using Docker. As of December, 2014, the only Docker respository that Red Hat supports is the one at registry.access.redhat.com. If you have access to a Docker image that is stored as a tarball, you can load that image into your Docker registry from your local file system.

docker pull: Use the pull option to pull an image from a remote repository. To pull the rhel base image from the Red Hat registry, type docker pull registry.access.redhat.com/rhel. To make sure that the image originates from the Red Hat registry, type the hostname of the registry, a slash, and the image name. The following command demonstrates this and pulls the rhel image from the Red Hat registry:

# docker pull registry.access.redhat.com/rhel

An image is identified by a repository name and a tag. The repository name rhel, when passed to the docker pull command without the name of a registry preceding it, is ambiguous and could result in the retrieval of an image that originates from an untrusted respository. To be more specific, you could add a tag, such as latest to form a name such as rhel:latest.

To see the images that resulted from the above docker pull command, type docker images:

# docker images
REPOSITORY                       TAG        IMAGE ID      CREATED       VIRTUAL SIZE
registry.access.redhat.com/rhel  0-21       e1f5733f050b  4 months ago  140.2 MB
registry.access.redhat.com/rhel  0          bef54b8f8a2f  4 months ago  139.6 MB
registry.access.redhat.com/rhel  0-23       bef54b8f8a2f  4 months ago  139.6 MB
registry.access.redhat.com/rhel  latest     bef54b8f8a2f  4 months ago  139.6 MB

docker load: If you have a container image stored as a tarball on your local system, you can load that image tarball so you can run it with the docker command on your local system. Here is how:

  1. With the Docker image tarball in your current directory, you can load that tarball to the local system as follows:

    # docker load -i rhel-server-docker-7.0-23.x86_64.tar.gz
  2. To push that same image to the registry running on your localhost, tag the image with your hostname (or "localhost") plus the port number of the docker-registry service (TCP port 5000). docker push uses that tag information to push the image to the proper repository:

    # docker tag bef54b8f8a2f localhost:5000/myrhel7
    docker push localhost:5000/myrhel7
    The push refers to a repository [localhost:5000/myrhel7] (len: 1)
    Sending image list
    Pushing repository localhost:5000/myrhel7 (1 tags)
    bef54b8f8a2f: Image successfully pushed 
    Pushing tag for rev [bef54b8f8a2f] on {http://localhost:5000/v1/repositories/myrhel7/tags/latest}
    ...
    

Investigating Docker images

If images have been pulled or loaded into your local registry, you can use the docker command docker images to view those images. Here's how to list the images on your local system:

# docker images
REPOSITORY   TAG      IMAGE ID      CREATED       VIRTUAL SIZE
redhat/rhel  latest   e1f5733f050b  4 weeks ago   140.2 MB
rhel         latest   e1f5733f050b  4 weeks ago   140.2 MB
redhat/rhel7 0        e1f5733f050b  4 weeks ago   140.2 MB
redhat/rhel7 0-21     e1f5733f050b  4 weeks ago   140.2 MB
redhat/rhel7 latest   e1f5733f050b  4 weeks ago   140.2 MB
rhel7        0        e1f5733f050b  4 weeks ago   140.2 MB
rhel7        0-21     e1f5733f050b  4 weeks ago   140.2 MB
rhel7        latest   e1f5733f050b  4 weeks ago   140.2 MB

NOTE: The default option to push an image or repository to the upstream Docker.io Index (docker push) is disabled in Red Hat version of the docker command. To push an image to a specific registry, identify the registry, its port number, and a tag that you designate in order to identify the image.

Investigating the Docker environment

Now that you have the docker and docker-registry services running, with a few containers available, you can start investigating the Docker environment and looking into what makes up a container. Run docker with the version and info options to get a feel for your Docker environment.

docker version: The version option shows which versions of different Docker components are installed. Notice that a newer docker package is available (yum update docker should take care of that in RHEL 7):

# docker version      Shows components/versions in use. Note that docker needs updating here.
Client version: 1.2.0
Client API version: 1.14
Go version (client): go1.3.1
Git commit (client): 2a2f26c/1.2.0
OS/Arch (client): linux/amd64
Server version: 1.2.0
Server API version: 1.14
Go version (server): go1.3.1
Git commit (server): 2a2f26c/1.2.0
Last stable version: 1.3.0, please update docker

docker info: The info option lets you see the locations of different components, such as how many local containers and images there are, as well as information on the size and location of Docker storage areas.

# docker info 
Containers: 3
Images: 5
Storage Driver: devicemapper
 Pool Name: docker-253:1-16826017-pool
 Pool Blocksize: 64 Kb
 Data file: /var/lib/docker/devicemapper/devicemapper/data
 Metadata file: /var/lib/docker/devicemapper/devicemapper/metadata
 Data Space Used: 1042.4 Mb
 Data Space Total: 102400.0 Mb
 Metadata Space Used: 1.3 Mb
 Metadata Space Total: 2048.0 Mb
Execution Driver: native-0.2
Kernel Version: 3.10.0-123.8.1.el7.x86_64
Operating System: Red Hat Atomic Host 7.0

Working with Docker containers

Docker images that are now on your system (whether they have been run or not) can be managed in several ways. The docker run command lets you say which command to run in a container. Once a container is running, you can stop, start, and restart it. You can remove containers you no longer need (in fact you probably want to).

Running Docker containers

When you execute a docker run command, you essentially spin up and create a new container from a Docker image. That container consists of the contents of the image, plus features based on any additional options you pass on the docker run command line.

The command you pass on the docker run command line sees the inside the container as its running environment so, by default, very little can be seen of the host system. For example, by default, the running applications sees:

  • The filesystem provided by the Docker image.

  • A new process table from inside the container (no processes from the host can be seen).

  • New network interfaces (by default, a separate docker network interface provides a private IP address to each containter via DHCP).

If you want to make a directory from the host available to the container, map network ports from the container to the host, limit the amount of memory the container can use, or expand the CPU shares available to the container, you can do those things from the docker run command line. Here are some examples of docker run command lines that enable different features.

EXAMPLE #1 (Run a quick command): This docker command runs the ip addr show eth0 command to see address information for the eth0 network interface within a container that is generated from the rhel image. Because this is a bare-bones container, we mount the /usr/sbin directory from the RHEL 7 host system for this demonstration (mounting is done by the -v option), because it contains the ip command we want to run. After the container runs the command, which shows the IP address (172.17.0.2/16) and other information about eth0, the container stops and is deleted (--rm).

# docker run -v /usr/sbin:/usr/sbin \
    --rm rhel /usr/sbin/ip addr show eth0
20: eth0:  mtu 1500 qdisc pfifo_fast state UP qlen 1000
    link/ether 4e:90:00:27:a2:5d brd ff:ff:ff:ff:ff:ff
    inet 172.17.0.10/16 scope global eth0
       valid_lft forever preferred_lft forever
    inet6 fe80::4c90:ff:fe27:a25d/64 scope link tentative 
       valid_lft forever preferred_lft forever

If you feel that this is a container you wanted to keep around and use again, consider assigning a name to it, so you can start it again later by name. For example, I named this container myipaddr:

# docker run -v /usr/sbin:/usr/sbin \
    --name=myipaddr rhel /usr/sbin/ip addr show eth0
20: eth0:  mtu 1500 qdisc pfifo_fast state UP qlen 1000
    link/ether 4e:90:00:27:a2:5d brd ff:ff:ff:ff:ff:ff
    inet 172.17.0.10/16 scope global eth0
       valid_lft forever preferred_lft forever
    inet6 fe80::4c90:ff:fe27:a25d/64 scope link tentative 
       valid_lft forever preferred_lft forever
# docker start -i myipaddr
22: eth0:  mtu 1500 qdisc pfifo_fast state UP qlen 1000
    link/ether 4e:90:00:27:a2:5d brd ff:ff:ff:ff:ff:ff
    inet 172.17.0.10/16 scope global eth0
       valid_lft forever preferred_lft forever
    inet6 fe80::4c90:ff:fe27:a25d/64 scope link tentative 
       valid_lft forever preferred_lft forever

EXAMPLE #2 (Run a shell inside the container): Using a container to launch a bash shell lets you look inside the container and change the contents. Here, I set the name of the container to mybash. The -i creates an interactive session and -t opens a terminal session. Without -i, the shell would open and then exit. Without -t, the shell would stay open, but you wouldn't be able to type anything to the shell.

Once you run the command, you are presented with a shell prompt and you can start running commands from inside the container:

# docker run --name=mybash -it rhel /bin/bash
[root@49830c4f9cc4/]#

Although there are very few applications available inside the base rhel image, you can add more software using the yum command. With the shell open inside the container, run the following commands:

[root@49830c4f9cc4/]# cat /etc/redhat-release
Red Hat Enterprise Linux Server release 7.1 (Maipo)
[root@49830c4f9cc4/]# ps
bash: ps: command not found
[root@49830c4f9cc4/]# yum install -y procps
[root@49830c4f9cc4/]# ps -ef
UID      PID    PPID  C STIME TTY       TIME  CMD
root       1       0  0 15:36 ?     00:00:00  /bin/bash
root      46       1  0 15:43 ?     00:00:00  ps -ef
[root@49830c4f9cc4/]# exit

Notice that the container is a RHEL 7.1 container. The ps command is not included in the rhel base image. However, you can install it with yum as shown above. To leave the container, type exit.

Although the container is no longer running once you exit, the container still exists with the new software package still installed. Use docker ps -a to list the container:

# docker ps -a
CONTAINER ID  IMAGE        COMMAND      CREATED        STATUS                    PORTS  NAMES
49830c4f9cc4  rhel:latest  "/bin/bash"  2 minutes ago  Exited (0) 25 minutes ago        mybash 
...

You could start that container again using docker start with the -ai options. For example:

# docker start -ai mybash
[root@a0aee493a605/]#

EXAMPLE #3 (Bind mounting log files): One way to make log messages from inside a container available to the host system is to bind mount the host's /dev/log device inside the container. This example illustrates how to run an application in a rhel container that is named log_test that generates log messages (just the logger command in this case) and directs those messages to the /dev/log device that is mounted in the container from the host. The --rm option removes the container after it runs.

# docker run --name="log_test" -v /dev/log:/dev/log --rm rhel logger "Testing logging to the host"
# journalctl -b | grep Testing
Apr 22 16:00:37 node1.example.com logger[102729]: Testing logging to the host

Investigating from outside of a Docker container

Let's say you have one or more Docker containers running on your host. To work with containers from the host system, you can open a shell and try some of the following commands.

docker ps: The ps option shows all containers that are currently running:

# docker ps
CONTAINER ID IMAGE       COMMAND     CREATED         STATUS       PORTS    NAMES
0d8b2ded3af0 rhel:latest "/bin/bash" 10 minutes ago  Up 3 minutes          mybash   

If there are containers that are not running, but were not removed (--rm option), the containers are still hanging around and can be restarted. The docker ps -a command shows all containers, running or stopped.

# docker ps -a
CONTAINER ID  IMAGE       COMMAND    CREATED      STATUS                PORTS  NAMES   
92b7ed0c039b  rhel:latest /bin/bash  2 days ago   Exited (0) 2 days ago        agitated_hopper        
eaa96236afa6  rhel:latest /bin/bash  2 days ago   Exited (0) 2 days ago        prickly_newton

See the section "Working with Docker containers" for information on starting, stopping, and removing containers that exist on your system.

docker inspect: To inspect the metadata of an existing container, use the docker inspect command. You can show all metadata or just selected items for the container. For example, to show all metadata for a selected container, type:

# docker inspect mybash
[{
    "Args": [],
        ...
        "Hostname": "a0aee493a605",
            "Image": "rhel",
            "Labels": {
                "Architecture": "x86_64",
                "Build_Host": "rcm-img04.build.eng.bos.redhat.com",
                "Name": "rhel-server-docker",
                "Release": "4",
                "Vendor": "Red Hat, Inc.",
                "Version": "7.1"
    ...

docker inspect --format: You can also use inspect to pull out particular pieces of information from a container. The information is stored in a hierarchy. So to see the container's IP address (IPAddress under NetworkSettings), use the --format option and the identity of the container. For example:

# docker inspect --format='{{.NetworkSettings.IPAddress}}' mybash
172.17.0.2

Examples of other pieces of information you might want to inspect include .Path (to see the command run with the container), .Args (arguments to the command), .Config.ExposedPorts (TCP or UDP ports exposed from the container), .State.Pid (to see the process id of the container) and .HostConfig.PortBindings (port mapping from container to host). Here's an example of .State.Pid and .HostConfig.PortBindings:

# docker inspect --format='{{.State.Pid}}' mybash
5007
# docker inspect --format='{{.HostConfig.PortBindings}}' mybash
map[8000/tcp:[map[HostIp: HostPort:8000]]]

Investigating within a running Docker container

To investigate within a running Docker container, you can use the docker exec command. With docker exec, you can run a command (such as /bin/bash) to enter a running Docker container process to investigate that container.

The reason for using docker exec, instead of just launching the container into a bash shell, is that you can investigate the container as it is running its intended application. By attaching to the container as it is performing its intended task, you get a better view of what the container actually does, without necessarily interrupting the container's activity.

Here is an example using docker exec to look into a running container named myrhel_httpd, then look around inside that container.

  1. Launch a container: Launch a container such as the myrhel_httpd container described in Building an image from a Dockerfile or some other Docker container that you want to investigate. Type docker ps to make sure it is running:

    # docker ps
    CONTAINER ID   IMAGE              COMMAND               CREATED         STATUS        PORTS                NAMES
    1cd6aabf33d9   rhel_httpd:latest  "/usr/sbin/httpd -DF  6 minutes ago   Up 6 minutes  0.0.0.0:80->80/tcp   myrhel_httpd
    
  2. Enter the container with docker exec: Use the container ID or name to open a bash shell to access the running container. Then you can investigate the attributes of the container as follows:

    # docker exec -it myrhel_httpd /bin/bash
    [root@1cd6aabf33d9 /]# cat /etc/redhat-release
    Red Hat Enterprise Linux Server release 7.1 (Maipo)
    [root@1cd6aabf33d9 /]# ps -ef
    UID        PID  PPID  C STIME TTY          TIME CMD
    root         1     0  0 08:41 ?        00:00:00 /usr/sbin/httpd -DFOREGROUND
    apache       7     1  0 08:41 ?        00:00:00 /usr/sbin/httpd -DFOREGROUND
    ...
    root        12     0  0 08:54 ?        00:00:00 /bin/bash
    root        35    12  0 08:57 ?        00:00:00 ps -ef
    [root@1cd6aabf33d9 /]# df -h
    Filesystem                          Size  Used Avail Use%   Mounted on
    /dev/mapper/docker-253:0-540464...  9.8G  414M  8.8G   5%   /
    tmpfs                               7.9G     0  7.9G   0%   /dev
    shm                                 64M      0   64M   0%   /dev/shm
    /dev/mapper/rhel_unused-root        137G   45G   92G  33%   /etc/hosts
    tmpfs                               7.9G  8.0K  7.9G   1%   /run
    tmpfs                               7.9G  184K  7.9G   1%   /run/secrets
    tmpfs                               7.9G     0  7.9G   0%   /proc/kcore
    [root@1cd6aabf33d9 /]# uname -r
    3.10.0-229.1.2.el7.x86_64
    [root@1cd6aabf33d9 /]# rpm -qa | less
    redhat-release-server-7.1-1.el7.x86_64
    basesystem-10.0-7.el7.noarch
    nss-softokn-freebl-3.16.2.3-9.el7.x86_64
    ...
    bash-4.2# free -m
                  total        used        free      shared  buff/cache   available
    Mem:          16046        6759         641          20        8645        8948
    Swap:          8071           2        8069
    [root@1cd6aabf33d9 /]# ip addr show eth0
    44: eth0:  mtu 1500 qdisc pfifo_fast state UP
        link/ether 92:b1:31:b2:79:69 brd ff:ff:ff:ff:ff:ff
        inet 172.17.0.14/16 scope global eth0
           valid_lft forever preferred_lft forever
        inet6 fe80::90b1:31ff:feb2:7969/64 scope link 
           valid_lft forever preferred_lft forever
    [root@1cd6aabf33d9 /]# exit
    

The commands just run from the bash shell (running inside the container) show you several things. The container holds a RHEL Server release 7.1 system. The process table (ps -ef) shows that the httpd command is process ID 1 (followed by five other httpd processes), /bin/bash is PID 12 and ps -ef is PID 35. Processes running in the host's process table cannot be seen from within the container. The container's file system consumes 414M of the 9.8G available root filesystem space.

There is no separate kernel running in the container (uname -r shows the host system's kernel: 3.10.0-229.1.2.el7.x86_64). The rpm -qa command lets you see the RPM packages that are included inside the container. In other words, there is an RPM database inside of the container. Viewing memory (free -m) shows the available memory on the host (although what the container can actually use can be limited using cgroups). The IP address in the container (172.17.0.14/16) is assigned to the container from the host system via DHCP. In this case, the host system has an interface named docker0 with an IP address of 172.17.42.1/16.

Starting and stopping containers

If you ran a container, but didn't remove it (--rm), that container is stored on your local system and ready to run again. To start a previously-run container that wasn't removed, use the start option. To stop a running container, use the stop option.

Starting containers: A docker container that doesn't need to run interactively can start with only the start option and the container ID or name:

# docker start myrhel_httpd
myrhel_httpd

To start a container so you can work with it from the local shell, use the -a (attach) and -i (interactive) options. Once the bash shell starts, run the commands you want inside the container and type exit to kill the shell and stop the container.

# docker start -a -i agitated_hopper
bash-4.2# exit

Stopping containers: To stop a running container that is not attached to a terminal session, use the stop option and the container ID or number. For example:

# docker stop myrhel_httpd
myrhel_httpd

The stop option sends a SIGTERM signal to terminate a running container. If the container doesn't stop after a grace period (10 seconds by default), docker sends a SIGKILL signal. You could also use the docker kill command to kill a container (SIGKILL) or send a different signal to a container. Here's an example of sending a SIGHUP signal to a container (if supported by the application, a SIGHUP causes the application to re-read its configuration files):

# docker kill --signal="SIGHUP" myrhel_httpd    

Removing containers

To see a list of containers that are still hanging around your system, run the docker ps -a command. To remove containers you no longer need, use the docker rm command, with the container ID or name as an option. Here is an example:

# docker rm goofy_wozniak    

You can remove multiple containers on the same command line:

# docker rm clever_yonath furious_shockley drunk_newton    

If you want to clear out all your containers, you could use a command like the following to remove all containers (not images) from your local system (make sure you mean it before you do this!):

# docker rm $(docker ps -a -q)    

Creating Docker images

So far we have grabbed some existing docker container images and worked with them in various ways. To make the process of running the exact container you want less manual, you can create a Docker image from scratch or from a container you ran that combines an existing image with some other content or settings.

Creating an image from a container

The following procedure describes how to create a new image from an existing image (rhel:latest) and a set of packages you choose (in this case an Apache Web server, httpd).

NOTE: For the current Red Hat Docker release, the default RHEL 7 Docker image you pull from Red Hat will be able to draw on RHEL 7 entitlements available from the host system. So, as long as your Docker host is properly subscribed and the repositories are enabled that you need to get the software you want in your container (and have Internet access from your Docker host), you should be able to install packages from RHEL 7 software repositories.

  1. Install httpd on a new container: Assuming you have loaded the rhel image from the Red Hat Customer Portal into your local system, and properly subscribed your host using Red Hat subscription management, the following command will:

    • Use that image as a base image
    • Get the latest versions of the currently installed packages (update)
    • Install the httpd package (along with any dependent packages)
    • Clean out all yum temporary cache files
    # docker run -i rhel:latest /bin/bash -c "yum clean all;  \
        yum update -y; yum install -y httpd; yum clean all"    
  2. Commit the new image: Get the new container's ID or name (docker ps -l), then commit that container to your local repository. When you commit the container to a new image, you can add a comment (-m) and the author name (-a), along with a new name for the image (rhel_httpd). Then type docker images to see the new image in your list of images.

    # docker ps -l
    CONTAINER ID  IMAGE          COMMAND              CREATED             STATUS                    PORTS  NAMES
    f6832df8da0a  redhat/rhel7:0 /bin/bash -c 'yum cl About a minute ago  Exited (0) 13 seconds ago        backstabbing_ptolemy4 
    # docker commit -m "RHEL with httpd" -a "Chris Negus" f6832df8da0a rhel_httpd
    630bd3ff318b8a5a63f1830e9902fec9a4ab9eade7238835fa6b7338edc988ac
    # docker images
    REPOSITORY   TAG     IMAGE ID      CREATED         VIRTUAL SIZE
    rhel_httpd   latest  630bd3ff318b  27 seconds ago  170.8 MB
    redhat/rhel  latest  e1f5733f050b  4 weeks ago     140.2 MB
    
  3. Run a container from new image: Using the image you just created, run the following docker run command to start the Web server (httpd) you just installed. For example:

    # docker run -d -p 8080:80 rhel_httpd:latest \
            /usr/sbin/httpd -DFOREGROUND
    

    In the example just shown, the Apache Web server (httpd) is listening on port 80 on the container, which is mapped to port 8080 on the host.

  4. Check that container is working: To make sure the httpd server you just launched is available, you can try to get a file from that server. Either open a Web browser from the host to address http://localhost:8080 or use a command-line utility, such as curl, to access the httpd server:

    # curl http://localhost:8080
    

Building an image from a Dockerfile

Once you understand how images and containers can be created from the command line, you can try building containers in a more permanent way. Building container images from Dockerfile files is by far the preferred way to create Docker formatted containers, as compared to modifying running containers and committing them to images.

The procedure here involves creating a Dockerfile file that includes many of the features illustrated earlier:

  • Choosing a base image
  • Installing the packages needed for an Apache Web server (httpd)
  • Mapping the server's port (TCP port 80) to a different port on the host (TCP port 8080)
  • Launching the Web server

While many features for setting up a Docker development environment for RHEL 7 are in the works, here are a few issues you should be aware of as you build your own docker containers:

  • Entitlements: Here are a few issues associated with Red Hat entitlements as they relate to containers:
    • If you subscribe your Docker host system using Red Hat subscription manager, when you build a Docker image on that host, the build environment automatically has access to the same Red Hat software repositories you enabled on the host.
    • To make more repositories available when you build a container, you can enable those repositories on the host or within the container.
    • Because the subscription-manager command is not supported within a container, enabling a repo inside the /etc/yum.repos.d/redhat.repo file is one way to enable or disable repositories. Installing the yum-utils package in the container and running the yum-config-manager command is another.
    • If you build a RHEL 6 container on a RHEL 7 host, it will automatically pick up RHEL 6 versions of the repositories enabled on your host.
    • For more information on Red Hat entitlements within containers, refer to the Docker Entitlements solution.
  • Updates: Docker containers in Red Hat Enterprise Linux do not automatically include updated software packages. It is your responsibility to rebuild your Docker images on occasion to keep packages up to date or rebuild them immediately when critical updates are needed. The "RUN yum update -y" line shown in the Dockerfile example below is one way to update your packages each time the Docker image is rebuilt.

  • Images: By default, docker build will use the most recent version of the base image you identify from your local cache. You may want to pull (docker pull command) the most recent version of an image from the remote Docker repository before you build your new image. If you want a specific instance of an image, make sure you identify the tag. For example, just asking for the image centos will pull the centos:latest image. If you wanted the image for CentOS 6, you should specifically pull the centos:centos6 image.

  1. Create project directories: On the host system where you have the docker and docker-registry services running, create a directory for the project:

    # mkdir -p httpd-project
    # cd httpd-project
    
  2. Create the Dockerfile file: Open a file named Dockerfile using any text editor (such as vim Dockerfile). Assuming you have registered and subscribed your host RHEL 7 system, here's an example of what the Dockerfile file might look like to build a Docker container for an httpd server:

    # My cool Docker image
    # Version 1
    
    # If you loaded redhat-rhel-server-7.0-x86_64 to your local registry, uncomment this FROM line instead:
    # FROM registry.access.redhat.com/rhel 
    # Pull the rhel image from the local repository
    FROM registry.access.redhat.com/rhel 
    
    MAINTAINER Chris Negus 
    
    # Update image
    RUN yum update -y
    # Add httpd package. procps and iproute are only added to investigate the image later.
    RUN yum install httpd procps iproute -y
    RUN echo container.example.com > /etc/hostname
    
    # Create an index.html file
    RUN bash -c 'echo "Your Web server test is successful." >> /var/www/html/index.html' 
  3. Checking the Dockerfile syntax (optional): Red Hat offers a tool for checking a Dockerfile file on the Red Hat Customer Portal. If you like, you can go to the Linter for Dockerfile page and check your Dockerfile file before you build it.

  4. Build the image: To build the image from the Dockerfile file, you need to use the build option and identify the location of the Dockerfile file (in this case just a "." for the current directory):

    NOTE: Consider using the --no-cache option with docker build. Using --no-cache prevents the caching of each build layer, which can cause you to consume excessive disk space.

    # docker build -t rhel_httpd .
    Uploading context  2.56 kB
    Uploading context 
    Step 0 : FROM registry.access.redhat.com/rhel 
     ---> f5f7ddddef7d
    Step 1 : MAINTAINER Chris Negus 
     ---> Running in 3c605e879c72
     ---> 77828ebe8f6f
    Removing intermediate container 3c605e879c72
    Step 2 : RUN yum update -y
     ---> Running in 9f45bb262dc6
    ...
     ---> Running in f44ea9eb6155
     ---> 6a532e340ccf
    Removing intermediate container f44ea9eb6155
    Successfully built 6a532e340ccf
    
  5. Run the httpd server in the image: Use the following command to run the httpd server from the image you just build (named rhel_httpd in this example):

    # docker run -d -t --name=myrhel_httpd \
            -p 80:80 -i rhel_httpd:latest \
            /usr/sbin/httpd -DFOREGROUND
    
  6. Check that the server is running: From another terminal on the host, type the following to check that you can get access the httpd server:

    # netstat -tupln | grep 80
    tcp6       0      0 :::80       :::*      LISTEN      26137/docker-proxy
    # curl localhost:80
    Your Web server test is successful.
    

Tagging Images

You can add names to images to make it more intuitive what they contain. Using the docker tag command, you essentially add an alias to the image, that can consist of several parts. Those parts can include:

registryhost/username/NAME:tag

You can add just NAME if you like. For example:

# docker tag 474ff279782b myrhel7

In the previous example, the rhel7 image had a image ID of 474ff279782b. Using docker tag, the name myrhel7 now also is attached to the image ID. So you could run this container by name (rhel7 or myrhel7) or by image ID. Notice that without adding a :tag to the name, it was assigned :latest as the tag. You could have set the tag to 7.1 as follows:

# docker tag 474ff279782b myrhel7:7.1

To the beginning of the name, you can optionally add a user name and/or a registry name. The user name is actually the repository on Docker.io that relates to the user account that owns the repository. Tagging an image with a registry name was show in Getting images from public Docker registries. Here's an example of adding a user name:

# docker tag 474ff279782b cnegus/myrhel7
# docker images | grep 474ff279782b
rhel7           latest  474ff279782b  7 months ago  139.6 MB
myrhel7         latest  474ff279782b  7 months ago  139.6 MB
myrhel7         7.1     474ff279782b  7 months ago  139.6 MB
cnegus/myrhel7  latest  474ff279782b  7 months ago  139.6 MB

Above, you can see all the image names assigned to the single image ID.

Saving and Importing Images

If you want to save a Docker image you created, you can use docker save to save the image to a tarball. After that, you can store it or send it to someone else, then reload the image later to reuse it. Here is an example of saving an image as a tarball:

# docker save -o myrhel7.tar myrhel7:latest

The myrhel7.tar file should now be stored in your current directory. Later, when you ready to reuse the tarball as a container image, you can import it to another docker environment as follows:

# cat myrhel7.tar | docker import - cnegus/myrhel7

Removing Images

To see a list of images that are on your system, run the docker images command. To remove images you no longer need, use the docker rmi command, with the image ID or name as an option. (You must stop any containers using an image before you can remove the image.) Here is an example:

# docker rmi rhel    

You can remove multiple images on the same command line:

# docker rmi rhel fedora    

If you want to clear out all your images, you could use a command like the following to remove all images from your local registry (make sure you mean it before you do this!):

# docker rmi $(docker images -a -q)    

Summary

At this point, you should be able to get Red Hat Docker installed with the docker and docker-registry services working. You should also have one or more Docker images to work with, as well as know how to run containers and build your own images.

Comments