I don’t see you copying the jar
into the container anywhere. You should try moving a VOLUME
declaration from Dockerfile
to the compose
file into the spring
service like this:
volumes:
- /my/project/dir:/app
And then inside Dockerfile you should point to the dir:
ENTRYPOINT [ "java","-jar","/app/build/libs/spring-project-0.1.0.jar" ]
Later on if you’d like to deploy it (for example) you should copy the project files directly into the image instead of utilizing the volumes
approach. So in Dockerfile
you’d then do:
COPY . /app
instead of VOLUME [..]
Putting it all together:
development:
Dockerfile:
FROM tomcat:9-jre8
RUN apt-get update && apt-get install librrds-perl rrdtool -y
ENTRYPOINT [ "java","-jar","/app/build/libs/spring-project-0.1.0.jar" ]
compose-file:
version: '2'
services:
[..]
spring:
container_name: spring-boot-project
build: .
links:
- db:db1
- db2:db2
depends_on:
- db
- db2
ports:
- "8081:8081"
restart: always
volumes:
- /my/project/dir:/app
deployment:
Dockerfile (that is placed inside project’s folder, docker build requires it’s build context to be in a current directory):
FROM tomcat:9-jre8
RUN apt-get update && apt-get install librrds-perl rrdtool -y
COPY . /app
ENTRYPOINT [ "java","-jar","/app/build/libs/spring-project-0.1.0.jar" ]
compose-file:
version: '2'
services:
[..]
spring:
container_name: spring-boot-project
build: .
links:
- db:db1
- db2:db2
depends_on:
- db
- db2
expose:
- "8081"
Я получаю сообщение об Error: Unable to access jarfile jar-runner.jar
при попытке запустить мою банку.
Dockerfile:
FROM anapsix/alpine-java
MAINTAINER bramhaag
CMD ["java", "-jar", "jar-runner.jar", "some param", "some param"]
Файл jar находится в /home/selfbot/, и я запускаю это с помощью Portainer. Вот как выглядит мой контейнер Portainer:
Как я могу сделать эту работу?
30 апр. 2017, в 00:39
Поделиться
Источник
3 ответа
В формате CMD [ ]
«exec» Docker попытается взглянуть на аргументы и высказать свое мнение об их полезности. «Невозможно получить доступ к jarfile» — это сообщение Docker, и это просто означает, что Docker имеет некоторые (неуказанные) проблемы с jarfile. Я сталкивался с этим, когда, например, имя jarfile содержало переменную ENV
. Видимо, Докер не мог с этим справиться.
Есть также CMD
формат «shell», CMD java -jar jar-runner.jar "some param" "some param"
. Это известно как формат оболочки, потому что Docker передает аргументы в /bin/sh -c
. В результате он не пытается переоценить значение аргументов. sh
в свою очередь тоже не пытается быть умным. И java
полностью способен использовать jar-runner.jar
.
jar-runner.jar
, что если у вас есть опечатка в jar-runner.jar
или вы поместили ее в неправильное место, то сообщение Docker может быть правильным. Обходной путь оболочки полезен, когда Docker не угадает.
MSalters
24 янв. 2019, в 15:08
Поделиться
Похоже, что у вас установлен том, поэтому, полагая, что вы правы, что файл jar доступен в контейнере через этот том, вам, вероятно, просто нужно указать путь к нему, чтобы java мог его найти.
CMD ["java", "-jar", "/home/selfbot/jar-runner.jar", "some param", "some param"]
Вы можете проверить, действительно ли файл доступен, запустив другую команду, чтобы просто показать содержимое данного каталога. Измените команду (в Portainer) на что-то вроде
ls -la /home/selfbot
И тогда вы можете проверить, действительно ли файл jar, где вы его думаете, читается ли он и т.д. Эта команда сразу выйдет, но его выход будет доступен в журнале контейнера.
Dan Lowe
29 апр. 2017, в 20:48
Поделиться
Ещё вопросы
- 1Ошибка выполнения Sonar Runner
- 0array_shift приводит к сбою php
- 1Есть ли инструмент Java, который позволяет проверять фрагменты кода?
- 0Лак 4, кеш страницы с печеньем
- 0Как я могу обработать данные после ‘/’ в URL, не считая их каталогом?
- 0Простое удаление из базы данных
- 1Форматирование XML для отображения в TextView?
- 0Не удается просмотреть результат при объединении 3 таблиц
- 0PHP, MYSQL: выбрать внутри цикла Loop?
- 1Обработка RunTimeException для класса
- 0Таблица полной ширины в контейнере с прокруткой
- 0regExp — Как найти, что моя переменная содержит только назначенную строку или нет ..?
- 0phpseclib не возвращает результатов даже по простой команде
- 0Как найти несколько столбцов в MySQL
- 0Шаблонный оператор шаблонного класса требует доступа к другим специализациям
- 0Как сравнить массив строк с массивом объектов, используя linq.js
- 0Калькулятор парсера бизонов
- 1Доступ к элементу в другой деятельности
- 1Как заменить одну запятую вне скобок
- 0Таблица не имеет раздела для значения 217
- 0Обложка + макет профиля
- 0Добавление метода поиска в jTable (jquery)
- 1Использование EF Code First для ключевых таблиц / баз данных по идентификатору пользователя
- 0Обеспечение безопасности типов в существующих навязчивых связанных списках C
- 0Проблема с параметрами URL
- 0Отправить изображение на контроллер API с Angularjs
- 1Отслеживание статистики Android Маркета
- 0указатель на массив символов, необработанное исключение
- 1Внешний контроль имени файла или пути сканирования Veracode
- 1ValueError: объект слишком глубокий для нужного массива в optimize.curve_fit
- 0Как отключить кнопку на Angular
- 1startActivity на Android
- 0Получение толщины контуров
- 1JavaScript сумма значений через объект
- 0использование значения в поле выбора в качестве входа для сохранения в таблицу sql
- 1angular ActivatedRoute.queryParams не позволяет использовать операторы rxjs?
- 1Java Внутренний Класс и Расширение
- 1android — переход от первого экрана к другому, выполняется с помощью Intent, но затмение дает некоторую ошибку
- 0Steptimer.getTotalSeconds в steptimer.h, возвращающем 0, c ++ visual studio 2013, приложение directx
- 0Как обрабатывать двоичные целые числа в средстве оценки выражений
- 0C ++: первый символ в очереди неверен
- 1Перехватить наOptionsItemSelected
- 0изображение накладывается на другое изображение
- 1Проверьте, является ли данный номер счастливым или нет
- 1Android — java.lang.VerifyError
- 0jquery: могу ли я динамически изменять href ссылки при наведении курсора?
- 1Как выделять определенные элементы из базы данных с помощью SimpleCursorAdapter
- 0Как показать-скрыть именованное представление в angular-ui-router
- 1Активность остается на экране после вызова другой активности из сервиса и завершения на Android
- 1Есть ли алгоритм, который может гарантировать порядок сбора при сохранении O (1) вставки / удаления?
Changing the default app for JAR files should fix this issue
by Matthew Adams
Matthew is a freelancer who has produced a variety of articles on various topics related to technology. His main focus is the Windows OS and all the things… read more
Updated on November 17, 2022
Reviewed by
Alex Serban
After moving away from the corporate work-style, Alex has found rewards in a lifestyle of constant analysis, team coordination and pestering his colleagues. Holding an MCSA Windows Server… read more
- The Unable to access the JAR file is a standard error when you don’t have compatible software to open it.
- Some users reported that using stable file openers fixed the issue for them.
- You can also fix this issue by uninstalling and downloading the latest version of Java.
XINSTALL BY CLICKING THE DOWNLOAD FILE
This software will repair common computer errors, protect you from file loss, malware, hardware failure and optimize your PC for maximum performance. Fix PC issues and remove viruses now in 3 easy steps:
- Download Restoro PC Repair Tool that comes with Patented Technologies (patent available here).
- Click Start Scan to find Windows issues that could be causing PC problems.
- Click Repair All to fix issues affecting your computer’s security and performance
- Restoro has been downloaded by 0 readers this month.
Java browser plug-ins might have gone out of fashion, but many programs run off Java. For example, you can open Java programs with JarFiles, among other software for opening JAR files.
However, some Java software users can’t always open JAR programs with the Unable to access JarFile error message popping up. This guide will show you some practical ways to get past this error message.
Why does it say unable to access jar?
The inability to access JarFile on Minecraft or Forge can be caused by mistakes on your path or issues with the software. Below are some of the prevalent causes:
- Outdated Java version: If your Java version is obsolete, you cannot access JarFile using the docker container. You need to update Java to the latest version.
- Wrong default program: Sometimes, this issue might be because you have not set the default program to open the JarFiles. Choosing Java as the default app for opening JAR files should fix this.
- Issues with the JAR file path: If the path to your jar file is incorrect, you can get this error. The solution here is to ensure the path is correct.
How can I fix the unable to access JarFile error?
Before proceeding to the fixes in this guide, try the preliminary troubleshooting steps below:
- Add .jar extension to the JAR file name
- Beware of spaces in the JAR file path
- Add quotes to the JAR file path if it contains space
- Move the JAR file to another folder
- Use a file opener software
If the fixes above fail to solve the issue, you can now move to the fixes below:
1. Update your Java version
- Press the Windows key + R, type appwiz.cpl, and click OK.
- Right-click the Java app and select the Uninstall option.
- Now, go to the official website to download the latest version of the Java app.
A broken or outdated app can cause the unable to access the JarFile issue. Downloading the latest version of the app should fix the problem.
2. Select Java as the default program for JarFiles
- Open File Explorer and the folder that includes your JAR file.
- Right-click the file and select Open with, and then Choose another app.
- Select Java if it’s listed among the default programs.
- If Java isn’t listed among the programs, select the Look for another app on this PC option.
- Then browse to the Java bin folder, select Java and press the Open button.
JAR file error messages usually pop up when Java isn’t configured as the default software for a JAR file. This can be the cause of the unable to access JarFile.
Setting Java as the default program should fix the issue here.
- How to Fix Error 5B00 on Canon Printers In No Time
- How to Resolve Microsoft Office Error Code 30204-44
3. Open the Jarfix Software
- Click jarfix.exe on this webpage to save the software to a folder.
- Now, open the folder and double-click the jarfix.exe option.
- The tool will start and fix issues with your jar file extension.
In some cases, the unable to access JarFile issue on IntelliJ can be because of problems with the file type associations. This Jarfix.exe software will help you fix this issue and restore normalcy on your PC.
Those are a few resolutions that might fix the unable to access JarFile error and kick-start your Java software. After that, you only need to follow the instructions carefully, and the issue should be resolved.
For further details on installing a JAR file in Windows 10, check our guide to make the process easy.
If you have any other questions, please leave them in the comments section below.
Still having issues? Fix them with this tool:
SPONSORED
If the advices above haven’t solved your issue, your PC may experience deeper Windows problems. We recommend downloading this PC Repair tool (rated Great on TrustPilot.com) to easily address them. After installation, simply click the Start Scan button and then press on Repair All.
Newsletter
Unable to access jar file in Docker image
I am loading a Docker image and trying to run under Shifter.
However, I had the following error: «Unable to access jarfile pilon-1.23.jar»
My script is here:
shifter —image=ttubb/pilon java -Xmx60G -jar pilon-1.23.jar
Here is the link to the docker image: https://hub.docker.com/r/ttubb/pilon/dockerfile
I guess that the jar file would be saved under a specific folder name, however, I cannot locate the folder. If you know any tips of finding the jar file location, could you please tell me how to do it? It will be of great help and learning for me.
Thanks.
genome
• 12k views
Hello, as docker file WORKDIR /software
, so .jar
will under /software
, maybe /software/pilon.jar
.
I don’t know Shifter, but on linux, you can run docker image use interactive mode(-it
), which way you can search your files derictly «inside» container. Maybe you can google how to run docker interactive mode on Shifter.
Login before adding your answer.
Образ Docker создан, но когда я хочу его запустить, он показывает эту ошибку:
Error: Unable to access jarfile rest-service-1.0.jar
Моя ОС — Ubuntu 18.04.1 LTS, и я использую docker build -t doc-service и docker run doc-service.
Это мой Dockerfile:
FROM ubuntu:16.04
MAINTAINER Frederico Apostolo <frederico.apostolo@blockfactory.com> (@fapostolo)
RUN apt-get update && apt-get -y upgrade
RUN apt-get install -y software-properties-common python-software-properties language-pack-en-base
RUN add-apt-repository ppa:webupd8team/java
RUN apt-get update && apt-get update --fix-missing && apt-get -y --allow-downgrades --allow-remove-essential --allow-change-held-packages upgrade
&& echo oracle-java8-installer shared/accepted-oracle-license-v1-1 select true | /usr/bin/debconf-set-selections
&& apt-get install -y --allow-downgrades --allow-remove-essential --allow-change-held-packages curl vim unzip wget oracle-java8-installer
&& apt-get clean && rm -rf /var/cache/* /var/lib/apt/lists/*
ENV JAVA_HOME /usr/lib/jvm/java-8-oracle/
run java -version
run echo $JAVA_HOME
#use locate for debug
RUN apt-get update && apt-get install -y locate mlocate && updatedb
#LIBREOFFICE START
RUN apt-get update && apt-get update --fix-missing && apt-get install -y -q libreoffice
libreoffice-writer ure libreoffice-java-common libreoffice-core libreoffice-common
fonts-opensymbol hyphen-fr hyphen-de hyphen-en-us hyphen-it hyphen-ru fonts-dejavu
fonts-dejavu-core fonts-dejavu-extra fonts-noto fonts-dustin fonts-f500 fonts-fanwood
fonts-freefont-ttf fonts-liberation fonts-lmodern fonts-lyx fonts-sil-gentium
fonts-texgyre fonts-tlwg-purisa
#LIBREOFFICE END
#font configuration
COPY 00-odt-template-renderer-fontconfig.conf /etc/fonts/conf.d
RUN mkdir /document-service /document-service/fonts /document-service/module /document-service/logs
# local settings
RUN echo "127.0.0.1 http://www.arbs.local http://arbs.local www.arbs.local arbs.local" >> /etc/hosts
# && mkdir /logs/ && echo "dummy" >> /logs/errors.log
#EXPOSE 2115
COPY document-service-java_with_user_arg.sh /
RUN chmod +x /document-service-java_with_user_arg.sh
RUN apt-get update && apt-get -y --no-install-recommends install
ca-certificates
curl
RUN gpg --keyserver ha.pool.sks-keyservers.net --recv-keys B42F6819007F00F88E364FD4036A9C25BF357DD4
RUN curl -o /usr/local/bin/gosu -SL "https://github.com/tianon/gosu/releases/download/1.4/gosu-$(dpkg --print-architecture)"
&& curl -o /usr/local/bin/gosu.asc -SL "https://github.com/tianon/gosu/releases/download/1.4/gosu-$(dpkg --print-architecture).asc"
&& gpg --verify /usr/local/bin/gosu.asc
&& rm /usr/local/bin/gosu.asc
&& chmod +x /usr/local/bin/gosu
ENV LANG="en_US.UTF-8"
# In case someone loses the Dockerfile
# Needs to be in the end so it doesn't invalidate unaltered cache whenever the file is updated.
RUN rm -rf /etc/Dockerfile
ADD Dockerfile /etc/Dockerfile
ENTRYPOINT ["/document-service-java_with_user_arg.sh"]
this is document-service-java_with_user_arg.sh:
#!/bin/bash
USER_ID=${LOCAL_USER_ID:-9001}
USER_NAME=${LOCAL_USER_NAME:-jetty}
echo "Starting user: $USER_NAME with UID : $USER_ID"
useradd --shell /bin/bash --home-dir /document-service/dockerhome --non-unique --uid $USER_ID $USER_NAME
cd /document-service
/usr/local/bin/gosu $USER_NAME "$@" java -jar rest-service-1.0.jar
Может ли кто-нибудь помочь мне в этом?
2 ответа
Лучший ответ
Основываясь на комментариях, вы должны добавить JAR при создании образа, указав в вашем Dockerfile:
COPY rest-service-1.0.jar /document-service/rest-service-1.0.jar
Вы также можете просто использовать:
COPY rest-service-1.0.jar /rest-service-1.0.jar
, и удалите cd /document-service
в сценарии точки входа, как и для изображений ubuntu:16.04
, рабочий каталог по умолчанию — /
. Я считаю, что установка рабочего каталога в скрипте более безопасна, поэтому вам следует просто выбрать первое решение.
Обратите внимание, что вы также можете использовать ADD
вместо COPY
(как вы уже делали в своем Dockerfile
), но здесь требуется только COPY
(прочтите этот пост, если хотите больше информация: В чем разница между командами COPY и ADD в файле Docker?).
Наконец, я предлагаю вам добавить строку COPY
в конце вашего Dockerfile
, чтобы при создании нового JAR изображение не было перестроено с нуля, а из существующего слоя, ускоряя время сборки.
0
norbjd
8 Янв 2019 в 11:36
Он ищет ошибку о рабочем каталоге, вы должны выбрать рабочий каталог для этого формата копии попробуйте WORKDIR / yourpath /
0
Servet TAS
8 Янв 2019 в 14:34
If you have recently tried to open a JAR package file, only to receive the error, “unable to access Jarfile,” this simply means that your computer either doesn’t have the right software to open the file, or you have the wrong file path. Other common reasons for getting this error is if you have an outdated version of Java, your computer is infected with malware, or the default program for opening your JAR files isn’t set correctly. Before we jump into the solutions for this, let’s take a look at what JAR is.
Understanding JAR Package Files
Java Archive or JAR is a package file format based on ZIP architecture. It is used to group together multiple Java class files, their metadata, and any resources these files need to run into one single package. The purpose of doing this is to then distribute the grouped files as needed for the running of applications and programs. In order to run the executable file in a JAR package, you must have the latest Java Run-Time Environment installed.
If you are getting the error, “unable to access Jarfile” it means that you are encountering one of the following problems:
- Your system has malware that is either preventing the Jarfile package to open.
- The Jarfile package is corrupted from malware.
- You do not have the latest Java Run-Time Environment installed.
- The default program for accessing JAR files isn’t set.
- The file path for the executable Jarfile package is incorrect.
The “unable to access Jarfile” error is quite a common one since there are many popular programs that use Java as their programming language. For instance, Netflix uses it along with Python for applications in its back-end, while Spotify uses it to stabilize data transfer, and Minecraft uses it for its launcher. Other popular programs and services that use Java include: Uber, Amazon, LinkedIn, Google, and Android OS.
1. Update Your Java to the Latest Version
The most likely reason that you are getting the, “unable to access Jarfile” error is due to an outdated version of Java. Unfortunately, outdated versions of Java Run-Time Environment are prone to security risks and loopholes, so keeping it updated is highly recommended regardless of whether you are getting the above error.
- In your computer’s search menu, type in “Control Panel”.
- In the control panel window, choose “uninstall a program” under programs.
- In the list of programs, scroll until you see Java. Or use the search program box in the top right-hand corner of the window.
- Take a look at the version number and see if it matches the latest release.
- If it doesn’t, uninstall the program by right-clicking on it.
- Choose “yes” when prompted.
- From the official Java website, download the latest version.
- Once downloaded, use the setup wizard to install Java.
Now, re-try opening your JAR package to see if the problem is fixed.
2. Make Java the Default Program for Opening JAR Packages
If you are still getting the “unable to access Jarfile” error after updating your Java Run-Time Environment to the latest version, then you may not have Java set as the default program to use for opening JAR packages.
- In your computer’s taskbar, open File Explorer.
- Find the folder that contains your JAR package.
- Right-click on the folder and choose “open,” and then Java.
- If Java is not listed, select “choose another app”.
- In the window that pops up, choose Java from the list. If it is not there, choose the “look for another app on this PC” option.
- Browse your computer for Java and find the program. Select it and hit the “open” option.
- A prompt window may open. If it does, choose “okay” and “open”.
- Double-click on your JAR package executable to open.
When browsing for Java on your computer in step 6, the most common place for it to be is in Program Files (x86)/Java/Java <Version>/Bin/Java.exe. Keep in mind that Java is usually installed to the default hard drive disk where your operating system is, unless you do a custom installation path. So, keep this in mind when trying to find Java on your computer.
3. Set Java as a Default Association Permanently
If you use a lot of programs or applications that use the Java Run-Time Environment, it is recommended that you set Java as a default association permanently in your computer, so that any JAR packages or files are automatically opened by Java.
- Press the Windows key and “I” on your keyboard to open Settings. Alternatively, type “settings” into your computer’s search menu.
- Click into the “apps” option in the Settings window.
- Choose “default apps” in the left-hand sidebar.
- Scroll until you see, “choose default apps by file type” and click it.
- Now, look for .jar in the list and click on “Choose a default” next to it.
- Find the Java Platform Program (Java Run-Time Environment) on your computer.
- Save the changes and exit.
Now restart your computer for the changes to take effect and see if you can open your JAR package without the, “unable to access Jarfile” error.
4. Check for Malware to Eliminate Infections Causing Trouble
If you are still getting the “unable to access Jarfile” error, it may be from malicious malware. A virus can easily exploit your registry and modify it to make JAR packages unusable. It is highly recommended that you run a thorough scan of your entire computer to look for malware. If you find some, remove it and uninstall Java. Repeat fix 1 in this list to reinstall.
5. Configure Hidden Files/Folders/Drives to Show
While not as common, sometimes hidden files, folders, and drives can cause the “unable to access Jarfile” error.
- In your computer’s taskbar, open File Explorer.
- At the top of the window, click on the “View tab”.
- Now click on the “Options” button to the far right.
- In the new window that opens, click on the “View tab” again.
- In the list, choose the “Show hidden files, folders, and drives” option.
- Hit Apply and then hit OK.
6. Repair Your Java Programs with Jarfix.
If you are using programs that launch with Java and they are not responding to you, no matter how many times you try to open the application, then it may be time to repair your JAR associations. To do this, simply download Jarfix, a lightweight program that fixes hijacked JAR associations, and run it.
7. Check the Documentation If You Are a Developer
If you are working in Java as a developer and come across the “unable to access Jarfile” error, it is likely that there is a minor mistake within the coding. It is recommended that you go back through and re-read to make sure that you have the right file path and the correct parameters for the code to work. Depending on what utility you are using to open and run your JAR packages, you may need to go back through and re-read the documentation on how to get it functioning properly.
Wrapping It Up
In most cases, the “unable to access Jarfile ” error will be solved by updating your Java Run-Time Environment to the latest version, but if it doesn’t solve the problem, please do try out the other methods on this list. Let us know in the comments below if we were able to help you!