What is a Docker? What is a container?
A container is an isolated lightweight environment to run an application. Docker is a platform that features commands and infrastructure for provisioning containers with usable applications. It has a cpan like repository of base images. Docker Hub hosts an official perl image based on Debian that works great and begins with perl and cpanm installed.
Creating a test application to containerize
mkdir build
cd build
# Requires mojolicious, you can git clone here also
mojo generate app myapp
Using Carton to handle CPAN dependencies
Create a file named 'cpanfile'.
# cpanfile
requires 'Mojolicious';
# and so on
Containerizing perl application
The image is built from a file 'dockerfile'. Each line is a layer in the image. The more static the content, the higher in the dockerfile it should be to utililze caching. For instance, in the below dockerfile, if 'cpanfile' changes, the new file is copied and all subsequent lines in the docker file are re-ran instead of pulled from cache. If alpine:latest on docker hub changes, being the first line, the whole image is rebuilt without cache. Alpine Linux is a popular choice for the first step in building containers because it is extremely small, coming in at 5mb.
Dockerfile
# dockerfile
FROM alpine:latest
RUN apk update && \
apk add perl \
perl-app-cpanminus \
ca-certificates \
wget \
make perl-dev libc-dev gcc && \
update-ca-certificates
RUN cpanm -n install Carton && rm -rf /root/.cpanm
WORKDIR /usr/src/myapp
COPY cpanfile /usr/src/myapp
RUN carton install && rm -rf /root/.cpanm
COPY myapp/ /usr/src/myapp
ENV PATH=$PATH:/usr/src/myapp/local/bin/
ENV PERL5LIB=/usr/src/myapp/local/lib/perl5/
CMD [ "script/myapp","daemon","-m","production","-l","http://*:8080" ]
Recap
We have:
- An application that lives in myapp.
- A cpanfile listing CPAN dependencies.
- A dockerfile that builds the image.
# Now to build the image
$ docker build -t myapp-container .
Commands to run
# Run the container with host's port 8081
# mapped to container's port 8080 using the cmd from dockerfile.
$ docker container run -p 8081:8080 -d myapp-container
# Explore your container using a shell
$ docker container run -it myapp-container sh
# Run the dev web server on port 8080
# and run the prod web server on port 8081
$ docker container run -p 8080:8080 -it -d myapp-container script/myap
+p daemon -m production -l http://*:8080
$ docker container run -p 8081:3000 -it myapp-container morbo script/m
+yapp
# Stop the container
$ docker container ls
$ docker container stop (insert container id)
# Save the container
$ docker save myapp-container > myapp-container.tar
More resources
|