
如何在服务器上搭建Shiny?
1.服务器及软件版本
NAME="Ubuntu"
VERSION="18.04.6 LTS (Bionic Beaver)"
ID=ubuntu
ID_LIKE=debian
PRETTY_NAME="Ubuntu 18.04.6 LTS"
VERSION_ID="18.04"
HOME_URL="https://www.ubuntu.com/"
SUPPORT_URL="https://help.ubuntu.com/"
BUG_REPORT_URL="https://bugs.launchpad.net/ubuntu/"
PRIVACY_POLICY_URL="https://www.ubuntu.com/legal/terms-and-policies/privacy-policy"
VERSION_CODENAME=bionic
UBUNTU_CODENAME=bionic
Docker version 24.0.2, build cb74dfc
Docker Compose version v2.18.1
2.docker-compose.yaml 文件配置
在服务器 /home 文件夹下,创建一个后缀为yaml的文件,将以下内容复制进入该文件中:
version: "3"
services:
shiny:
image: rocker/shiny:4.4.1
container_name: shiny
ports:
- "3838:3838"
# volumes:
# - /home/shiny/shinyapps/:/opt/shiny-server/samples/
# - /home/shiny/shinylog/:/var/log/shiny-server/
restart: unless-stopped
请注意我注释掉的部分,代表的含义为将本机的目录(前:)映射到shiny容器中对应的目录(:后)中(该目录代表的是shiny运行R APP目录和相关的运行日志),但是不要上来就运行该命令,否则会将空文档进行映射,无法正常运行shiny。
3.使用docker compose创建shiny
然后在服务器上运行下面两行代码。
cd /home
docker compose up -d
然后shiny就会启动,如果顺利的话,在浏览器的地址栏中输入ip:3838
就可以进入到如下的页面:
到现在为止马上就要成功了,不要着急,现在还差最后一步。
4.拷贝APP文件夹
使用如下命令拷贝shiny容器内的APP和log文件夹。
docker cp shiny:/opt/shiny-server/samples/. /home/shiny/shinyapps/
docker cp shiny:/var/log/shiny-server/. /home/shiny/shinylog/
然后回到第2步,将#号删除。
再使用如下代码重启shiny 容器:
docker compose down
docker compose up -d
此时会发现/home/shiny/shinyapps/路径下多了一些文件,如下所示:
其中welcome.html为欢迎页面,可以使用html语言自己编辑哦。sample-apps里面有两个示例app,分别为hello和rmd。
5.运行自己的APP
如果你想让shiny运行新的APP,那么就需要往下图的路径下传文件就可以了。如下示例,我新建了一个test文件夹,在里面上传了一个app.R文件
其内容如下所示,是一个求平方的APP(然后也可以分开写成server 和 ui两个文件,具体的可以参考两个示例app):
# app.R
library(shiny)
# Define UI for application
ui <- fluidPage(
# Application title
titlePanel("Hello, Shiny!"),
# Sidebar layout with input and output definitions
sidebarLayout(
sidebarPanel(
# Input: Numeric entry for the user's number
numericInput("num",
"Enter a number:",
value = 1,
min = 1,
max = 100)
),
mainPanel(
# Output: Display the square of the number entered by the user
textOutput("square")
)
)
)
# Define server logic
server <- function(input, output) {
# Calculate the square of the input number and render it in the UI
output$square <- renderText({
paste("The square of the number is:", input$num^2)
})
}
# Run the application
shinyApp(ui = ui, server = server)
然后进入ip:3838/sample-apps/test/
就可以运行你刚刚写好的APP了,愉快的进行平方计算吧!o(* ̄︶ ̄*)o
6.后记
下面是不基于docker搭建的shiny,供参考:
https://posit.co/download/shiny-server/ #下载和搭建shiny-server
https://posit.co/download/rstudio-server/ #Download RStudio Server v2024.04.2+764
https://cran.rstudio.com/bin/linux/ubuntu/ #Ubuntu Packages For R - Brief Instructions
还有关于如何给容器中的R安装package,可以在服务器终端上使用 docker exec -it shiny /bin/bash
进入容器中,然后键入R
,进入R语言,然后安装自己想要的package就可以了。