Movatterモバイル変換


[0]ホーム

URL:


Skip to content
DEV Community
Log in Create account

DEV Community

Cover image for Development Environments with Docker
Erika Heidi
Erika Heidi

Posted on • Edited on • Originally published ateheidi.dev

     

Development Environments with Docker

Docker is a software used to build and runcontainers. Unlike virtual machines, containers do not emulate an entire operating system, relying on the host OS to provide an isolated filesystem that consumes less resources than traditional VMs, but still provide a fully functional runtime based on a chosen operating system.

The container model as a high-level overview

The build steps necessary to (re)create a Docker container image are defined in aDockerfile. This file may contain special instructions to install packages, create users, and run arbitrary system commands.

Container images can be hosted in a remote registry that allow images to be pulled from different locations. The default Docker registry isDocker Hub, but there are many others. When using images from registries other than Docker Hub, you'll need to specify the registry URL along the image identifier.

Pulling Images from a Registry

Thepull command is used to pull images from a remote registry. It is not mandatory to run this command before running an image, as the pull will happen automatically. However, if you already have a local copy of an image, you'll need to run thepull command in order to obtain an updated version of the image.

docker pull registry/image
Enter fullscreen modeExit fullscreen mode

For example, this will pull thePHP Chainguard Image to your local machine:

docker pull cgr.dev/chainguard/php
Enter fullscreen modeExit fullscreen mode

You should see output similar to this:

Using default tag: latestlatest: Pulling from chainguard/php1e4853eb9712: PullcompleteDigest: sha256:387acb900179de11ca5a56c3ebbb6f29d2df88cb488d50fc9736ab085f27520dStatus: Downloaded newer imageforcgr.dev/chainguard/php:latestcgr.dev/chainguard/php:latest
Enter fullscreen modeExit fullscreen mode

Running Containers

Therun command is used to execute the entry point defined by your image Dockerfile. Depending on the image and how it is used, you may need to provide additional parameters to the command.

docker run registry/image
Enter fullscreen modeExit fullscreen mode

For example, the following command will execute the PHP image we pulled in the previous section, with the--version flag to obtain the PHP version:

docker run cgr.dev/chainguard/php--version
Enter fullscreen modeExit fullscreen mode
PHP 8.2.12(cli)(built: Nov 15 2023 15:30:03)(NTS)Copyright(c) The PHP GroupZend Engine v4.2.12, Copyright(c) Zend Technologies
Enter fullscreen modeExit fullscreen mode

Running Containers in Interactive Mode

Many (maybe even most) container images run a single command and are terminated afterwards. It is the case with regular PHP images that are meant to run scripts. There is no interaction once the process of execution is initiated.

Some images will require some type of interaction from the user. That is often the case with images that run an interactive application such asbash. In those cases, you'll need to provide the-it argument when running Docker:

docker run-it registry/image
Enter fullscreen modeExit fullscreen mode

For example, this will execute thewolfi-base image and land you in a shell inside the newly created container:

docker run-it cgr.dev/chainguard/wolfi-base
Enter fullscreen modeExit fullscreen mode

Running Ephemeral Containers

To remove a container immediately after it is terminated, add the-rm parameter to thedocker run command:

docker run--rm registry/image
Enter fullscreen modeExit fullscreen mode

This is especially useful for running quick commands that don't generate relevant output that needs to be shared or persisted, as with our first example that checked for the PHP version. We could rewrite that command to the following:

docker run--rm cgr.dev/chainguard/php--version
Enter fullscreen modeExit fullscreen mode

And this will prevent Docker from keeping the state of this container, which is good for saving resources.

Checking Container Status

To have a full list of active and inactive containers currently registered in the system, run:

docker ps-a
Enter fullscreen modeExit fullscreen mode

Note: When the-a parameter is not provided, Docker will list only containers that are currently running.

You should get output similar to this:

CONTAINER ID   IMAGE                    COMMAND                CREATED          STATUS                      PORTS     NAMES26272c21399c   cgr.dev/chainguard/php"/bin/php --version"   10 minutes ago   Exited(0) 10 minutes ago             musing_hermann
Enter fullscreen modeExit fullscreen mode

The first time we executed the command to obtain the PHP version of the container, we didn't use the--rm flag. That's why the container is listed here - it's inactive, but its state is saved.

Using Volume Shares

When running development environments, it's crucial that you're able to edit your code in your local machine, while being able to execute and test it inside the container. To enable that, you can useDocker volumes. Volumes are used to share the contents of a predefined path in your host machine to a location inside the container.

The following command will create a volume sharing the contents of LOCAL_FOLDER in the host machine with REMOTE_FOLDER inside the container.

docker run-v LOCAL_FOLDER:REMOTE_FOLDER registry/image
Enter fullscreen modeExit fullscreen mode

Use Case and Example

Let's say you want to run a PHP script without having to install PHP (could be any other language). You want to be able to make changes to the file and test it in an isolated environment.

Create a folder in your home directory for this demo:

mkdir ~/docker-democd ~/docker-demo
Enter fullscreen modeExit fullscreen mode

Next, create a new file and copy the following contents to it:

<?phpecho"Testing Docker PHP Dev Env";print_r($argv);
Enter fullscreen modeExit fullscreen mode

Save the file asdemo.php.

Now you can use a Docker image to run this code. The following command will create an ephemeral container to execute code shared inside the container:

docker run--rm-v${PWD}:/app cgr.dev/chainguard/php demo.php
Enter fullscreen modeExit fullscreen mode

The${PWD} shell variable contains the current directory location. The volume will share the current directory with the/app location in the container, which is the workdir (the default directory) for that image. With the files shared in the default workdir, you can refer to the script simply asdemo.php.

Purging Docker Resources

Some resources are not removed once a container is terminated; that is the case with named volumes. Images can also leave a big footprint in your system, think gygabites of space from unused layers and old images.

Theprune command can be used to clean up unused resources and free up space occupied by them. For instance, to purge unused volumes:

docker volume prune
Enter fullscreen modeExit fullscreen mode
WARNING! This will remove anonymous local volumes not used by at least one container.Are you sure you want to continue? [y/N]
Enter fullscreen modeExit fullscreen mode

The same logic applies toimages andnetworks. To perform a complete system purge, run:

docker system prune
Enter fullscreen modeExit fullscreen mode

You should get a warning message confirming what is going to be removed. Typey to confirm.

WARNING! This will remove:  - all stopped containers  - all networks not used by at least one container  - all dangling images  - all dangling build cacheAre you sure you want tocontinue?[y/N]
Enter fullscreen modeExit fullscreen mode

Unused resources accumulate with time, so it's good to run this command every once in a while. Depending on how you're using Docker, you may be able to free up a lot of disk space with this command.

Resources to Learn More

TheWhat are Containers? guide from Chainguard Academy has a nice high level overview of containers and images. For more technical specifications and reference docs, check the officialDocker Documentation which covers all components in the Docker container ecosystem.

For considerations about container security, check this Academy guide onSelecting a Base Image and the introduction toSoftware Supply Chain Security, which should give you a better understanding of security considerations when bringing your images to Production.

Bonus: Docker Cheat Sheet

Docker Cheat Sheet

Top comments(10)

Subscribe
pic
Create template

Templates let you quickly answer FAQs or store snippets for re-use.

Dismiss
CollapseExpand
 
jonesrussell profile image
Russell Jones
Web Developer
  • Location
    Canada
  • Education
    nil
  • Work
    Software Developer
  • Joined

🎵 Dah-Dah-Dah-Dock…er! 🎵 Docker is the Beethoven of tech, orchestrating a symphony of efficiency in our development environments. But just like a symphony, it can get complex when you start conducting with Kubernetes.

Docker is indeed a tool that everyone in the field should embrace. It’s not just about containerization, it’s about transforming the way we think about and interact with our development environments.

Erika, your insightful exploration into Docker is a beacon for us all. Keep these enlightening posts coming, we’re all aboard for the journey! 🌊

CollapseExpand
 
erikaheidi profile image
Erika Heidi
Open sourceress and machine enchantress. Passionate about open source, coding, and writing.
  • Location
    The Hague
  • Work
    Developer Experience Engineer at Chainguard
  • Joined

Haha that's lovely. Thank you!

CollapseExpand
 
cherryramatis profile image
Cherry Ramatis
A trans woman who loves to code 🧙‍♀️
  • Pronouns
    She,Her,Ela,Dela
  • Work
    Web full stack developer
  • Joined

Awesome content around docker! really amazing didactics thanks

I always rundocker system prune -a to save some GB on my hard disk haha

CollapseExpand
 
erikaheidi profile image
Erika Heidi
Open sourceress and machine enchantress. Passionate about open source, coding, and writing.
  • Location
    The Hague
  • Work
    Developer Experience Engineer at Chainguard
  • Joined

Thank you 🥹🫶

CollapseExpand
 
hectorlaris profile image
Héctor Serrano
Software Engineer
  • Education
    University
  • Work
    Software Engineer
  • Joined

Tks a lot!

CollapseExpand
 
kehoecj profile image
Clayton Kehoe
Software Engineer @Boeing | Maintainer of https://github.com/Boeing/config-file-validator | DevSecOps | Go | Python | 🚀 City Alabama
  • Joined

Nice guide!

CollapseExpand
 
erikaheidi profile image
Erika Heidi
Open sourceress and machine enchantress. Passionate about open source, coding, and writing.
  • Location
    The Hague
  • Work
    Developer Experience Engineer at Chainguard
  • Joined

Thank you! 🫶

CollapseExpand
 
fernandafernandes profile image
Fernanda Fernandes Machado
  • Joined

Obrigada Erika pelo excelente artigo! Por favor, continue🙏 Adoro sua didática. Seus tutoriais já salvaram minha vida várias vezes kkk

CollapseExpand
 
erikaheidi profile image
Erika Heidi
Open sourceress and machine enchantress. Passionate about open source, coding, and writing.
  • Location
    The Hague
  • Work
    Developer Experience Engineer at Chainguard
  • Joined

muito obrigada <3

CollapseExpand
 
xucian profile image
xucian
hardcore unity3d gamedev since 2013, turned into ml/genai/devops generalist since 2019. maximizing the amount of good in the world
  • Work
    Everything
  • Joined

any thoughts about separating different envs through compose?

Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment'spermalink.

For further actions, you may consider blocking this person and/orreporting abuse

Open sourceress and machine enchantress. Passionate about open source, coding, and writing.
  • Location
    The Hague
  • Work
    Developer Experience Engineer at Chainguard
  • Joined

More fromErika Heidi

DEV Community

We're a place where coders share, stay up-to-date and grow their careers.

Log in Create account

[8]ページ先頭

©2009-2025 Movatter.jp