Perl in Docker
| The perl image | |
| Run one-liners | |
| Mount your script | |
| Modules in an image |
The perl image
Docker runs Perl without installing it on the host. The official perl image on the hub carries ready builds for each release line, and cpanm is already inside.
The perl:5.40 tag follows the 5.40 line, so it is a good default for this course. Add -slim for a smaller image without the compiler, and drop it when a module needs to build from source.
docker pull perl:5.40
Pulling first makes the next commands instant and shows the download progress in one place. The image is a few hundred megabytes, so do it once.
Run one-liners
The fastest check prints the version from inside a fresh container. The container is removed automatically after it runs:
Print the Perl version from Docker
docker run --rm perl:5.40 perl -v
This is perl 5, version 40, subversion 0 (v5.40.0) built for x86_64-linux
A longer program fits in -e as well, as long as you quote it for your shell. This one uses the module from lesson 42:
docker run --rm perl:5.40 perl -MJSON::PP -e "print JSON::PP->new->canonical->encode({b => 2, a => 1})"
{"a":1,"b":2}
Both modules come with Perl, which is why no install step is needed. The next section handles the case where they do not.
Mount your script
To run your own file, mount the current folder into the container and set it as the working folder. Then ask the container Perl to run your script by name:
Run main.pl from the current folder
docker run --rm -v "$PWD":/app -w /app perl:5.40 perl main.pl
hello from Docker
The mount shares files both ways, so edits on the host are visible inside the container at once. That is the same loop as running Perl locally, with the interpreter coming from the image.
On Windows, replace $PWD with the absolute path using forward slashes, or run the command from Git Bash or WSL where $PWD works.
Modules in an image
Modules installed during a plain run live only as long as that container. That is handy for a quick trial and useless for a repeatable build. For anything you will run again, write a Dockerfile:
FROM perl:5.40-slim
WORKDIR /app
COPY cpanfile .
RUN cpanm --installdeps .
COPY . .
CMD ["perl", "todo", "list"]
Copying the cpanfile before the rest of the code lets Docker cache the module layer. Rebuilds after a code change reuse the installed modules and finish in seconds instead of minutes.
docker build -t todo .
docker run --rm todo
The second command runs the image with no arguments, so the CMD starts the list command. Pass arguments after the image name to override it: docker run --rm todo list.
This is also the cleanest way to test the capstone from lesson 46 on a machine without Perl, and the same recipe works for the log report in lesson 47 once you add its modules to the cpanfile.
Next: Perl course
Article author: Arthur Isaev