In this post I want to describe how to dockerize a simple Shiny App. Docker is a great way of sharing and deploying projects. You can download it here.
Resources:
- R Docker tutorial, recommended for Docker beginners.
- Running a shiny app in a docker container by Mark Sellors (which is an updated and more complete version of this post).
Assume you have a project folder structure as follows:
.
+-- project.Rproj
+-- app.R
+-- R
| +-- script_1.R
| +-- script_2.R
+-- data
| +-- data_df.rds
| +-- raw_data.csv
- The script
app.R
contains the code of the Shiny application. - The folder
R
contains auxiliary scripts. - The folder
data
contains a csv and an rds file which might be nessesary for the application (cleaned data set, for example).
To create a docker image you need to create a Dockerfile, which is a simple text file located in the same directory as app.R
. The name of the file must be Dockerfile
. A common structure of this file is the following:
# get shiny serves plus tidyverse packages image
FROM rocker/shiny-verse:latest
# system libraries of general use
RUN apt-get update && apt-get install -y \
sudo \
pandoc \
pandoc-citeproc \
libcurl4-gnutls-dev \
libcairo2-dev \
libxt-dev \
libssl-dev \
libssh2-1-dev
# install R packages required
# (change it dependeing on the packages you need)
RUN R -e "install.packages('shiny', repos='http://cran.rstudio.com/')"
RUN R -e "install.packages('shinydashboard', repos='http://cran.rstudio.com/')"
RUN R -e "devtools::install_github('andrewsali/shinycssloaders')"
RUN R -e "install.packages('lubridate', repos='http://cran.rstudio.com/')"
RUN R -e "install.packages('magrittr', repos='http://cran.rstudio.com/')"
RUN R -e "install.packages('glue', repos='http://cran.rstudio.com/')"
RUN R -e "install.packages('DT', repos='http://cran.rstudio.com/')"
RUN R -e "install.packages('plotly', repos='http://cran.rstudio.com/')"
# copy the app to the image
COPY project.Rproj /srv/shiny-server/
COPY app.R /srv/shiny-server/
COPY R /srv/shiny-server/R
COPY data /srv/shiny-server/data
# select port
EXPOSE 3838
# allow permission
RUN sudo chown -R shiny:shiny /srv/shiny-server
# run app
CMD ["/usr/bin/shiny-server.sh"]
To build the docker image you can run on the console (where the Dockerfile
is located):
docker build -t my-shiny-app .
To create a container just run:
docker run --rm -p 3838:3838 my-shiny-app
You can share your image on Docker Hub or as a .tar file.