Docker start linux gui

Записки программиста

Осилил запуск GUI-приложений в Docker

Как мы совсем недавно уже выясняли, есть целый ряд проблем, которые можно решить запихиванием приложений в Docker-контейнеры, в том числе десктопных приложений. Никакой хакер не поломает вас через браузер. Настроенную систему можно быстро разложить у нового сотрудника или на своем новом ноуте. Всякий мусор, необходимый только одной программе, можно изолировать от остальной системы и снести одной командой. Никаких конфликтов зависимостей. Можно попытаться обновить программу, и если что-то в новой версии сломалось, просто перезапустить контейнер без коммита. Можно даже запускать браузер на одной машине, IDE на другой, а рулить всем этим с ноутбука, пробросив на него X11! Самое интересное, что запускать GUI приложения в Docker оказалось на удивление просто.

Примечание: В этой заметке используются наработки из поста Зачем нужен Docker и практика работы с ним. Вам может захотеться прочитать его прежде, чем следовать далее. Или перечитать, если успели подзабыть содержание.

Собственно, половина ответа уже содержится во введении. Если вы зайдете на VDS, где вы поднимали OpenVPN (технарей без своего VPN не существует!), по SSH с флагом -X , проверив при этом, что в /etc/ssh/sshd_config есть строчка X11Forwarding yes , скажете sudo apt-get install x11-apps , а затем xcalc , то у вас запустится калькулятор, как если бы он работал на локальной машине. При этом приложение работает на VDS, а ваш X-сервер просто используется для отрисовки окошек.

Docker, как мы выясняли, правильно использовать не по те-еретическому принципу «по приложению на контейнер, потому что так правильно™», а беря за основу baseimage. Это значит, что контейнер для нас мало чем отличается от VDS, и то же самое пробрасование X11 должно работать. Другой вопрос, что делать со звуком? Но эту проблему мы тоже скоро решим. А пока что давайте попробуем запустить в контейнере веб-браузер Chromium хотя бы без звука.

Запускаем контейнер, используя созданный ранее образ baseimage-ssh:

Заходи в контейнер:

Пытаемся поставить x11-apps. В моем случае система внезапно сообщила, что слыхом не слыхивала о таких чудесах, поэтому пришлось скопировать файл /etc/apt/sources.list с хост-системы. После этого все получилось:

Перезаходим по SSH с флагом -X , пытаемся запустить xcalc. Лично я увидел ошибку:

Запуск SSH с флагом -v помог понять ее причину:

После установки xauth в гостевой системе все заработало. Пробуем кое-что посерьезнее:

Chromium у меня так просто тоже не стал запускаться, сказав:

Беглое гугление привело меня в обсуждение в группах Google, благодаря которому, а также благодаря приведенным в нем ссылкам, я понял, что это такая багофича Chromium при работе во всяких изолированных окружениях, и что правильно запускать его так:

Следуте однако отметить, что шрифты могут вас шокировать. Вам может захотеться сначала сказать:

Теперь имеем Chromium, как Chromium. Так и не скажешь, что под Docker запущен.

На первый взгляд, в контейнере как-то без разницы, под рутом ты сидишь или нет. Но под рутом можно случайно удалить или испортить файлы, которые удалять или портить не хотелось, и придется откатываться к последнему коммиту, потеряв все другие сделанные изменения. Поэтому на всякий случай заведем нового пользователя:

Под рутом говорим:

Появится одна или несколько строчек вроде таких:

Переключаемся на юзера:

Для каждой ранее уведенной строчечки говорим:

В дальнейшем так далать не понадобится, все сохраняется в файлики.

Для удобства можно прописать алиас в .bashrc. В целом все отлично работает, страницы грузятся быстро, даже видео на YouTube можно смотреть. Только звука пока что нет. Давайте же это исправим!

В гостевой системе:

Запускаем paprefs, во вкладке Network Server ставим галочку Enable network access to local sound devices, а также Don’t require authentication. Затем:

В netstat -tuwpan должны увидеть, что процесс pulseaudio слушает порт 4713. Вам может захотеться добавить парочку правил фаервола, если по умолчанию вы разрешаете кому угодно стучатся на любые ваши порты. Если после выполнения приведенной выше команды ничего не изменилось, попробуйте:

У меня как-то не с первого раза получилось, но в итоге все заработало без необходимости перезагружать Ubuntu.

Теперь пробрасываем порт на гостевую систему:

В гостевой системе говорим:

… и звук пошел! Самое главное теперь — не забудьте сделать commit!

Что интересно, контейнеры не обязательно должны быть запущены локально. Вы можете проделать все описанное выше на удаленной машине и это тоже будет работать, в том числе ssh -X на машину, а потом ssh -X в гостевую систему на этой машине успешно пробросит вам GUI. Учтите однако, что хорошо работать это будет только в локальной сети. Если вы в Москве, а сервер в Амстердаме, пользоваться проброшенным интерфейсом будет нереально, я проверял. Возможно, тут имеет смысл попробовать VNC.

Как оказалось, моя любимая IntelliJ IDEA таким образом также прекрасно запускается. Похоже, можно без проблем запускать в Docker-контейнерах практически любые приложения, кроме, возможно, чего-то вроде игр. Если вдруг кому-то интересно, размер экспортированного образа с IDE, компилятором Scala, SBT, а также кучей джавных/скальных библиотек, скопированных с хост-системы, получился 9 Гб без сжатия и 5.4 Гб после сжатия. Накладных расходов на виртуализацию замечено не было, я даже несколько раз сравнивал скорость компиляции проекта в хост-системе и в Docker — никакой разницы.

А какие GUI-приложения вы пробовали запускать в Docker и с какими проблемами при этом столкнулись?

Источник

linux-notes.org

Запуск GUI-приложения в Docker

Хочу поведать историю о том, как я запустил GUI-приложение в Docker. некоторые спросят, зачем? Ну есть много причин, вот некоторые из них:

  • Нет нужного пакета/утилиты под твою ОС.
  • Проверить что получится.
Читайте также:  Как windows оценивает ноутбук

Запуск GUI-приложения в Docker

Начну с теории и закончу примерами.

Архитектура X window system 101

В *NIX системах, приложение GUI имеет роль «X-клиента». Каждый раз, когда он перерисовывает свое содержимое, последовательность графических команд кодируется все в X протокол используя библиотеку (обычно Xlib) и передается в сокет X11. На другом конце, X-сервер считывает такие команды из сокета и отображает их на дисплей:

Контейнерезированные (Containerizing) GUI приложения

Взглянув на архитектуру X window системы, ясно то, что для того, чтобы наши контейнеризованные графические приложения могли рисовать на экране, нам нужно предоставить ему доступ к сокету X11 (запись), и нам нужен X-сервер для использования и рендеринга графики команд на экран.

Мы можем подойти к этой проблеме с двух сторон:

  • Мы можем связать xvfb и VNC-сервер с нашим образом контейнера.
  • Мы можем совместно использовать сокет X11 хоста с контейнером в качестве внешнего раздела.

Первый подход — это тот, который проще реализовать, он работает из коробки и клиенты VNC доступны. В то же время мы должны учитывать, что xvfb создает представление в памяти дисплея, а VNC сохраняет в памяти последнюю обновленную область, поэтому в худшем случае мы получаем размер буфера кадра, выделенного дважды в каждый экземпляр докер-контейнера.

Совместное использование сокета X11 хоста с контейнером — это гораздо более модульное решение, которое позволяет использовать более компактный файл Docker, и он позволяет владельцу X-сервера переключать реализацию в соответствии с ее потребностями (возможно, X-сервер нашего хоста может быть даже самой xvfb).

Для начала, установим вспомогательное ПО:

И так, сейчас я приведу несколько примеров использования docker чтобы запустить графическое ПО внутри докер-контейнера. Самый простой способ сделать это, это выполнить:

Это самые простые способы для запуска.

Поддержка 3D hardware acceleration:

Поддержка звука (Audio):

Поддержка Webcam:

Используем date/time как и на хосте:

PS: Некоторые дистрибутивы не используют /etc/localtime, чтобы установить часовой пояс, в этих случаях вам нужно будет проверить, как он это делает и «реплицировать» в контейнер.

Проброс конфигов в контейнер:

Подключаем Video-game controller:

Это были примеры запусков. Сейчас приведу наглядные примеры….

-=== Запуск mysql-workbench в Docker ===-

После чего, я создам машину для тестов, буду использовать docker-machine:

Машина создана, подключаемся к ней:

Внутри созданной докер-машины, создаем:

Где нужно изменить «ENV DISPLAY :0» строку на свой «DISPLAY», чтобы узнать его, выполните:

Получите вывод (Если у вас MacOS X):

Получите вывод (Если у вас Linux. Проверял на CentOS 6):

Ну что, создаем контейнер:

Запускаем контейнер и прокидываем в него сокет. Контейнер автоматически стартует MySQL-Workbench при запуске:

PS: Можно прописать переменную:

Потом запуск будет проходить вот так:

Честно сказать, у меня не получилось запустить данный контейнер на моем macbook, получил ошибку:

Дубль 2, пробую выполнить все тоже, но на CentOS 6:

ИЛИ, для всех юзеров:

Но это не верное решение, берем свой eth0 ИП:

Так же, пробросим переменную для дисплея:

После этого, запускаю:

Вылезли другие ошибки… Посидел пару часов, я исправил ошибки на маке (описание решения, в самом низу статьи), ну а сейчас — я запускаю контейнер:

Или (Но 1-й вариант лучше как по мне):

Шикарно! Все заработало!

-=== Запуск FireFox в Docker ===-

Существует несколько различных вариантов запуска GUI-приложений внутри Docker контейнера:

  • С использованием SSH с пересылкой X11
  • С использованием SSH с пересылкой VNC
  • Разделение сокетов между хостом и докер-контейнером

Самый простой способ — заключается в том, чтобы разделить мой сокет X11 с контейнером и использовать его напрямую. Идея довольно проста, и вы можете легко попробовать попробовать запустить контейнер Firefox, используя следующий файл Docker:

И вот что получилось:

Данный пример приводился на CentOS 6, но у меня есть еще MacOS X и я бы хотел все же подружить все это дело!

Ставим пакет для MacOS X:

Открываем натройки, переходим во вкладку «security» и выставляем все галочки (2 шт):

Хочу добавить следующее, я много перерыл в интернете, но мало что полезного нашел. И да, вот как у меня выглядят конфигы ssh.

Приведу еще пример.

-=== Запуск spotify в Docker ===-

PS: У меня тут используется несколько интерфейсов, но я взял ИП с eth1.

Или, для MacOS X:

Не буду собирать контейнер с Dockerfile, возьму готовый имедж:

Я тут пробросил звуковое устройство во внутрь самого контейнера.

Вот это шайтаны додумались)))

На маке я пока не понял как это сделать 🙁

-=== Запуск wireshark в Docker ===-

PS: У меня тут используется несколько интерфейсов, но я взял ИП с eth1.

Или, для MacOS X:

Или посмотреть все ИП на всех интерфейсах:

Не буду собирать контейнер с Dockerfile, возьму готовый имедж:

Вот и все, статья «Запуск GUI-приложения в Docker» завершена.

Добавить комментарий Отменить ответ

Этот сайт использует Akismet для борьбы со спамом. Узнайте, как обрабатываются ваши данные комментариев.

Источник

Getting started with Docker & Running GUI Application inside it

Mostly we run our servers or tasks inside Docker Container, but ever imagined — we can even launch GUI applications inside Docker Container & can access them from the Docker Host system. Stick with me till the end of this blog to learn the basics of Docker & how to achieve this fantastic practical…

Docker :

On 2013, Solomon Hykes introduced the biggest innovation of decades called Docker & within 2 years docker & container technology became the most demanding technology in the Industry.

  • Previously when it was taking 10 to 15 minutes to configure & setup a server on VM or over Cloud Computing, there Docker was able to launch the entire OS with pre-configured server in just 1 or 2 seconds. Industry started booming & every company started implementing DevOps solutions like Container Technology.
  • In the mean time Docker also started improving & the biggest profit Docker had at that time was — It was an open-source product. Means thousands of Techy guys started implementing new new ideas on Docker & it also started improving over the years.
  • Today container technology is so powerful that it can do each & everything we want. We can setup multi node clusters using Container like Kubernetes Cluster, Storage Cluster, Database Cluster, Compute Cluster, Network Cluster etc. In fact nowadays Container Technology is so powerful that we can even setup entire Private Cloud Computing in it.
  • There’s limitless possibilities Container Technology has but in this blog I gonna talk about one of the very much interesting possibility of Docker Container that is we gonna run GUI applications like firefox, gedit etc. inside Docker Container.

Note : I will talk about the basics of Docker at first, so that anyone who’s reading this blog can learn this amazing tool.

What is a Container ?

Let’s think in this way — Why we need OS ?

  • Because we want to run some program in it. OS has the capability to contact to hardware to run our Programs. Now as per the constraints we can only run one OS on top of one RAM & CPU at a particular point of time.
  • If you notice this constraint, then you will always feel your resources are being wasted because most of the time we don’t utilize the full hardware that we buy. To overcome the challenge of this constraint, Engineers came up with the solution called Virtualization means we will create the hardware spaces virtually so that we can run multiple OS on one hardware.
  • This solves the challenge of resource wastage for some limit but ultimately it was taking so much time to provision, then setting up the VM & then run the programs etc. Finally if you think once again the 1st question why we need OS, the answer is always the same, we want to run some programs & without OS it’s impossible to run any program.
  • So why to waste time in Provisioning the OS. To solve this issue Industry started using Container Technology. The best part of Container Technology is it can launch & login to one entirely fresh new OS in just 1 or 2 seconds. Also if you has the pre-configured Docker Image then you can launch your entire OS with the running server in it in just few seconds.
  • Container is like an isolated environment to run your application. It same like having multiple VM in your system. Similar like VM, Container also has it’s own OS specific commands, own network card, own OS specific files & folders, own processes, own storage etc.
Читайте также:  Windows size and tcp

Let’s go to the Practical :

  • Remember one thing if you want to do virtualization then you need at least one virtualization software to be installed on your system like Oracle VirtualBox, Hyper-V, VM-Ware, KVM etc. Similarly if you want containerization then you need the respective software.
  • There are lots of program that has the capabilities to create container like Docker, CRI-O, Podman, Rocket etc. But in this blog our focus is on Docker Technology. Let’s start by installing the software of Docker. Now there are two versions of Docker — Community Edition which is free to use & Enterprise Edition which requires license to use. We are going to use Docker Community Edition (docker-ce).

Pre-requisite :

Although we can run Docker inside Windows System but I’m gonna use Linux OS as my Docker Host. Means on my RedHat Linux 8 system I will install Docker Software. If you don’t have RHEL8 system with you, then you can also use CentOS/Fedora system too.

I’m using a Windows system & in it I have installed Oracle VirtualBox Software, there I have one RHEL8 VM. This will be my Docker Host. You can use any Linux OS to install Docker but based on the Flavour of the Linux Distribution, Docker Installation process will be different. But once we install the Docker, then everything is exactly same no matter whatever OS you are using.

Note: I’m not showing how to install Docker because there are lots of article on Google on “How to install docker-ce on CentOS8/RHEL8”. Just follow any of the one & for reference I’m sharing one link — https://www.linuxtechi.com/install-docker-ce-centos-8-rhel-8/

Once you download & install the Docker software, start the docker service.

What is a Docker Image ?

To install any OS, we need respective image. Image contain all the data, that we need to run that particular OS.

  • Similarly to launch a Docker Container or OS we need to use Docker Image. There are thousands of image on Docker repository called Docker Hub —https://hub.docker.com/ .
  • Most of the images on Docker Hub is free to use. Let’s say we want a Ubuntu 18.04 OS, then to launch it using Docker we at first need the Docker Image of Ubuntu 18.04. Go to Docker Hub & search “Ubuntu” & you will find the official image.

Now we gonna use Docker to download that image on our local system, in my case it’s RHEL8 system which is my Docker Host. Run the below mentioned command to download the image…

Next you will see this output mentioned in the below screenshot…

Once image download is successful, run the below mentioned command to see how many images you have locally downloaded…

Let’s download one more image called centos 8. Similar like previous command run…

Now we have two Docker images. Let’s go to the next step.

Launching the Container :

Now here you will see the actual power of Docker. As I had already told that we need Docker Image to launch the container. So, now as we have the images, let’s launch one container. Run the below mentioned command to launch a container…

  • We have given our docker container a name called “os1” & it’s launched using ubuntu:18.04 image. Here this “-it” option means after container launch provide me one “Interactive Terminal”.
  • You will see within 1 second, your terminal changed & now you are inside a new terminal. The most interesting part here is this terminal is not your Docker Host (RHEL8) terminal. It’s the terminal of Ubuntu Container.
  • That means now you will see none of the RHEL8 specific commands are working. For example run “yum repolist” command & you will see “yum command not found”. Because in Ubuntu we use “apt-get” to install the software. If you run “apt list” it will start working. For reference see the below mentioned screenshot…
Читайте также:  Запуск компьютера с флешки windows

Now as you are on your local Docker Host GUI, there open one new terminal without closing the previous one. Here run…

You will see one container is running & how much time before it was launched. Now let’s do one more very much interesting thing. Run the below mentioned command & launch one centos:8 container…

As soon as you run the command, now you are inside “centos:8” docker container. To check that run “yum repolist” & you will see it’s working fine. But if you run “apt list” it will say “apt command not found”. For reference check the below mentioned screenshot…

Isolation of the Containers :

I have already told previously that Container is like an isolated space with it’s own OS respective command, files & folders, own network adaptor, own processes, storage etc. Let’s check if those things are there or not. On os2 run the below mentioned command…

Note : If you see yum is not installing the software, then on your base OS, stop the firewalld service & then restart the docker & then launch again one new container with a different name & it will start working.

  • Once this software is installed you will get some commands on your container. Now run “ifconfig” command & you will see your container has one entirely new IP address with respective network adaptor. Next if you run “ls” command you will see it has all the OS specific files & folders.
  • Now to exit from the container just run “exit” & you will see you again landed on the terminal of your Docker Host. Next if you run “docker ps” you will see no container is running, but if you want to see the stopped containers then you can run “docker ps -a”. For reference check the below mentioned screenshot…

To start a stopped container & then to go inside the running container, you can use the below mentioned commands respectively…

There are lots of concepts of Docker, but as a basic starting this much knowledge is enough to go to the next practical.

Creating Docker Image :

Now it’s time to create our own Docker Image. There are two methods of doing this — Docker Commit Command & Dockerfile concept. I want to talk about Dockerfile.

  • Remember one thing that our final goal is not just to launch the OS. Our final goal is to run our programs inside container. So, for that either we can launch one container & can run our program, but in Industry we run thousands of containers in parallel.
  • So, it’s impossible to run program manually in every container. So what we can do is — we can put all the information inside Docker Image & once we launch the container our program will also start & till the time our program is running container will run & once program close, we don’t need the container so it will automatically stop.

This is the reason we want to create Docker Image & for that purpose we use “Dockerfile” concept. On your Docker Host create one folder to use as your workspace & then inside that workspace create one file using vim or gedit editor. One small thing to note here is that the file name should be “Dockerfile”. Each & every character of the file name should be exactly same like I had written.

Now in your “Dockerfile” put the below mentioned code…

  • Save the file & now let’s understand how this file has been written. Dockerfile has it’s own specific keywords to tell certain things. Like we used “FROM” keyword to tell use “centos:8” image & on top of this image we will run our program.
  • Next to run any program we need to install the required software, for that we used “RUN” keyword & tell to use “yum install net-tools -y” command to install the software. Just note one thing that as we are using “centos:8” to run our program that’s why to install the software we used “yum” command.
  • Next we used “CMD” keyword to tell as soon as the container launch run “ifconfig” command.

Now it’s time to build the image. For that run the below mentioned command on the same folder where you have the “Dockerfile”…

  • Here we are using “docker build” command to build the image & to give the image a name/tag we are using “-t” option. Then we give “myimage” tag to our image & the “v1” is the version of our image. You can give any tags & version name you want, but try to be logical in this part.
  • Lastly we use “.” to tell docker that Dockerfile is there where we are running “docker build” command. If you notice here we are not mentioning any file name because I already told you this name of the file “Dockerfile” is fixed. So, on your currently workspace it will look for that file & start building the image from it.

Now you will see your image is ready. So again to create the container from this image you can run…

  • Here we are not using “-it” because we don’t want to use the terminal of our container. So, as you can now realize we are launching one container & gave the name “myos1”, & it’s launching from our own created Docker Image. For reference check the below screenshot…

Источник

Оцените статью